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

// import { cookieService } from '../token/cookie.service';

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

import { RegisterDto, LoginDto } from './auth.dto';
import { authService } from './auth.service';


/**
 * EN: Auth Controller
 * VI: Controller xác thực
 */
export class AuthController {
  /**
   * EN: Register endpoint
   * VI: Endpoint đăng ký
   */
  async register(req: Request, res: Response): Promise<void> {
    try {
      const data = RegisterDto.parse(req.body);
      const result = await authService.register(data, req);

      // Set cookies
      // cookieService.setAuthCookies(res, result.tokens);

      res.status(201).json({
        success: true,
        data: {
          user: {
            id: result.user.id,
            email: result.user.email,
            username: result.user.username,
          },
          tokens: result.tokens,
        },
      });
    } 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: 'REGISTRATION_FAILED',
          message: getErrorMessage(error) || 'Registration failed',
        },
      });
    }
  }

  /**
   * EN: Login endpoint
   * VI: Endpoint đăng nhập
   */
  async login(req: Request, res: Response): Promise<void> {
    try {
      const data = LoginDto.parse(req.body);
      const result = await authService.login(data, req);

      if (result.user.mfaRequired) {
        res.status(200).json({
          success: true,
          data: {
            mfaRequired: true,
            userId: result.user.id,
          },
        });
        return;
      }

      // Set cookies
      // cookieService.setAuthCookies(res, result.tokens);

      res.status(200).json({
        success: true,
        data: {
          user: {
            id: result.user.id,
            email: result.user.email,
            username: result.user.username,
          },
          tokens: result.tokens,
        },
      });
    } 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(401).json({
        success: false,
        error: {
          code: 'LOGIN_FAILED',
          message: getErrorMessage(error) || 'Login failed',
        },
      });
    }
  }

  /**
   * EN: Logout endpoint
   * VI: Endpoint đăng xuất
   */
  async logout(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: 'Not authenticated' },
        });
        return;
      }

      await authService.logout(userId, undefined, req);
      // cookieService.clearAuthCookies(res);

      res.status(200).json({
        success: true,
        data: { message: 'Logged out successfully' },
      });
    } catch (error: unknown) {
      res.status(500).json({
        success: false,
        error: {
          code: 'LOGOUT_FAILED',
          message: getErrorMessage(error) || 'Logout failed',
        },
      });
    }
  }

  /**
   * EN: Refresh token endpoint
   * VI: Endpoint làm mới token
   */
  async refreshToken(req: Request, res: Response): Promise<void> {
    try {
      const refreshToken = req.body.refreshToken; // cookieService.getTokenFromCookie(req, 'refresh') || req.body.refreshToken;

      if (!refreshToken) {
        res.status(400).json({
          success: false,
          error: { code: 'REFRESH_TOKEN_REQUIRED', message: 'Refresh token required' },
        });
        return;
      }

      const result = await authService.refreshToken(refreshToken, req);

      // Update cookies if new refresh token provided
      if (result.refreshToken) {
        // cookieService.setAuthCookies(res, {
        //   accessToken: result.accessToken,
        //   refreshToken: result.refreshToken,
        // });
      }

      res.status(200).json({
        success: true,
        data: result,
      });
    } catch (error: unknown) {
      res.status(401).json({
        success: false,
        error: {
          code: 'REFRESH_FAILED',
          message: getErrorMessage(error) || 'Token refresh failed',
        },
      });
    }
  }

  /**
   * EN: Verify email endpoint
   * VI: Endpoint xác minh email
   */
  async verifyEmail(req: Request, res: Response): Promise<void> {
    res.status(501).json({
      success: false,
      error: {
        code: 'NOT_IMPLEMENTED',
        message: 'Email verification is not yet implemented / Xác minh email chưa được triển khai'
      },
      timestamp: new Date().toISOString()
    });
  }

  /**
   * EN: Forgot password endpoint
   * VI: Endpoint quên mật khẩu
   */
  async forgotPassword(req: Request, res: Response): Promise<void> {
    res.status(501).json({
      success: false,
      error: {
        code: 'NOT_IMPLEMENTED',
        message: 'Forgot password is not yet implemented / Quên mật khẩu chưa được triển khai'
      },
      timestamp: new Date().toISOString()
    });
  }

  /**
   * EN: Reset password endpoint
   * VI: Endpoint đặt lại mật khẩu
   */
  async resetPassword(req: Request, res: Response): Promise<void> {
    res.status(501).json({
      success: false,
      error: {
        code: 'NOT_IMPLEMENTED',
        message: 'Reset password is not yet implemented / Đặt lại mật khẩu chưa được triển khai'
      },
      timestamp: new Date().toISOString()
    });
  }
}

export const authController = new AuthController();
