import { Request, Response } from 'express';
import { z } from 'zod';

import { getErrorMessage } from '../../utils/error-utils';

import { ChangePasswordDto } from './auth.dto';
import { changePasswordService } from './change-password.service';

/**
 * EN: Change Password Controller
 * VI: Controller đổi mật khẩu
 */
export class ChangePasswordController {
  /**
   * EN: Change password endpoint
   * VI: Endpoint đổi mật khẩu
   */
  async changePassword(req: Request, res: Response): Promise<void> {
    try {
      const userId = (req as any).user?.id || (req as any).user?.sub;
      
      if (!userId) {
        res.status(401).json({
          success: false,
          error: { code: 'UNAUTHORIZED', message: 'Authentication required' },
        });
        return;
      }

      const data = ChangePasswordDto.parse(req.body);
      
      await changePasswordService.changePassword(
        userId,
        data.currentPassword,
        data.newPassword,
        req
      );

      res.json({
        success: true,
        data: { message: 'Password changed successfully' },
      });
    } catch (error: unknown) {
      if (error instanceof z.ZodError) {
        res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'Invalid input',
            details: error.issues,
          },
        });
        return;
      }

      res.status(400).json({
        success: false,
        error: {
          code: 'CHANGE_PASSWORD_FAILED',
          message: getErrorMessage(error) || 'Failed to change password',
        },
      });
    }
  }
}

export const changePasswordController = new ChangePasswordController();
