const RegisterUserCommand = require('../../application/auth/commands/RegisterUserCommand');
const LoginUserCommand = require('../../application/auth/commands/LoginUserCommand');

/**
 * Auth Controller
 * Authentication endpoints using CQRS Commands with cookie-based JWT
 */
class AuthController {
  constructor(registerUserCommandHandler, loginUserCommandHandler, jwtService) {
    this.registerUserCommandHandler = registerUserCommandHandler;
    this.loginUserCommandHandler = loginUserCommandHandler;
    this.jwtService = jwtService;
  }

  /**
   * POST /api/auth/register - User regisztráció
   */
  async register(req, res) {
    try {
      const { name, email, password } = req.body;

      const command = new RegisterUserCommand(name, email, password);
      const result = await this.registerUserCommandHandler.handle(command);

      // Set JWT token in httpOnly cookie
      res.cookie(
        this.jwtService.getCookieName(),
        result.token,
        this.jwtService.getCookieOptions()
      );

      res.status(201).json({
        message: 'User registered successfully',
        data: {
          user: result.user
        }
      });
    } catch (error) {
      // Validációs hibák -> 400
      const status = error.message.includes('required') || 
                     error.message.includes('already exists') ||
                     error.message.includes('Invalid') ||
                     error.message.includes('must be') ? 400 : 500;

      res.status(status).json({ error: error.message });
    }
  }

  /**
   * POST /api/auth/login - User bejelentkezés
   */
  async login(req, res) {
    try {
      const { email, password } = req.body;

      const command = new LoginUserCommand(email, password);
      const result = await this.loginUserCommandHandler.handle(command);

      // Set JWT token in httpOnly cookie
      res.cookie(
        this.jwtService.getCookieName(),
        result.token,
        this.jwtService.getCookieOptions()
      );

      res.status(200).json({
        message: 'Login successful',
        data: {
          user: result.user
        }
      });
    } catch (error) {
      // Validációs vagy auth hibák -> 401
      const status = error.message.includes('Invalid') || 
                     error.message.includes('required') ? 401 : 500;

      res.status(status).json({ error: error.message });
    }
  }

  /**
   * POST /api/auth/logout - User kijelentkezés
   */
  async logout(req, res) {
    try {
      // Clear the auth cookie
      res.clearCookie(this.jwtService.getCookieName(), {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'strict',
        path: '/'
      });

      res.status(200).json({
        message: 'Logout successful'
      });
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  }
}

module.exports = AuthController;
