import { Request, Response, NextFunction } from 'express';
import authService from '../../../application/services/AuthService';

export class AuthController {
  static register = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const result = await authService.register(req.body);
      return res.status(201).json({ success: true, data: result, message: 'Pendaftaran berhasil' });
    } catch (error) {
      next(error);
    }
  };

  static login = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const result = await authService.login(req.body.email, req.body.password);
      return res.status(200).json({ success: true, data: result, message: 'Login berhasil' });
    } catch (error) {
      next(error);
    }
  };

  static refresh = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const { refreshToken } = req.body;
      if (!refreshToken) return res.status(400).json({ success: false, message: 'Refresh token diperlukan' });
      const tokens = await authService.refresh(refreshToken);
      return res.status(200).json({ success: true, data: tokens, message: 'Token diperbarui' });
    } catch (error) {
      next(error);
    }
  };

  static logout = (req: Request, res: Response) => {
    res.clearCookie('token');
    return res.status(200).json({ success: true, message: 'Logout berhasil' });
  };

  static forgotPassword = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const result = await authService.forgotPassword(req.body.email);
      return res.status(200).json({ success: true, data: result, message: 'Reset link dikirim' });
    } catch (error) {
      next(error);
    }
  };

  static resetPassword = async (req: Request, res: Response, next: NextFunction) => {
    try {
      await authService.resetPassword(req.body.token, req.body.password);
      return res.status(200).json({ success: true, message: 'Password berhasil direset' });
    } catch (error) {
      next(error);
    }
  };
}

export default AuthController;
