import { Request, Response, NextFunction } from 'express';
import * as authService from '../services/auth.service';
import { sendSuccess, sendError } from '../utils/apiResponse';
import { 
  registerSchema, loginSchema, changePasswordSchema, 
  forgotPasswordSchema, resetPasswordSchema, refreshTokenSchema 
} from '../validators/auth.validator';

export const register = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const validated = registerSchema.parse(req);
    const result = await authService.register(validated.body, req.ip, req.headers['user-agent'] as unknown as string | undefined | undefined);
    return sendSuccess(res, 201, 'Inscription réussie', result);
  } catch (error: any) {
    if (error.name === 'ZodError') {
      return sendError(res, 400, 'Données invalides', error.errors);
    }
    return sendError(res, 400, error.message);
  }
};

export const login = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const validated = loginSchema.parse(req);
    const result = await authService.login(validated.body, req.ip, req.headers['user-agent'] as unknown as string | undefined | undefined);
    return sendSuccess(res, 200, 'Connexion réussie', result);
  } catch (error: any) {
    if (error.name === 'ZodError') {
      return sendError(res, 400, 'Données invalides', error.errors);
    }
    return sendError(res, 401, error.message);
  }
};

export const refresh = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const validated = refreshTokenSchema.parse(req);
    const result = await authService.refreshTokens(validated.body.refreshToken, req.ip, req.headers['user-agent'] as unknown as string | undefined | undefined);
    return sendSuccess(res, 200, 'Token rafraîchi', result);
  } catch (error: any) {
    if (error.name === 'ZodError') {
      return sendError(res, 400, 'Données invalides', error.errors);
    }
    return sendError(res, 401, error.message);
  }
};

export const logout = async (req: Request, res: Response, next: NextFunction) => {
  try {
    if (!req.user) {
      return sendError(res, 401, 'Non authentifié');
    }
    await authService.logout(req.user.id, req.ip, req.headers['user-agent'] as unknown as string | undefined | undefined);
    return sendSuccess(res, 200, 'Déconnexion réussie');
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const changePassword = async (req: Request, res: Response, next: NextFunction) => {
  try {
    if (!req.user) {
      return sendError(res, 401, 'Non authentifié');
    }
    const validated = changePasswordSchema.parse(req);
    await authService.changePassword(req.user.id, validated.body.current_password, validated.body.new_password, req.ip, req.headers['user-agent'] as unknown as string | undefined | undefined);
    return sendSuccess(res, 200, 'Mot de passe modifié avec succès');
  } catch (error: any) {
    if (error.name === 'ZodError') {
      return sendError(res, 400, 'Données invalides', error.errors);
    }
    return sendError(res, 400, error.message);
  }
};

export const forgotPassword = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const validated = forgotPasswordSchema.parse(req);
    await authService.forgotPassword(validated.body.email, req.ip, req.headers['user-agent'] as unknown as string | undefined | undefined);
    // Même réponse qu'on ait trouvé un compte ou non (sécurité)
    return sendSuccess(res, 200, 'Si un compte correspond à cette adresse, un lien de réinitialisation a été envoyé.');
  } catch (error: any) {
    if (error.name === 'ZodError') {
      return sendError(res, 400, 'Données invalides', error.errors);
    }
    return sendError(res, 400, error.message);
  }
};

export const resetPassword = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const validated = resetPasswordSchema.parse(req);
    await authService.resetPassword(validated.body.token, validated.body.new_password, req.ip, req.headers['user-agent'] as unknown as string | undefined | undefined);
    return sendSuccess(res, 200, 'Mot de passe réinitialisé avec succès');
  } catch (error: any) {
    if (error.name === 'ZodError') {
      return sendError(res, 400, 'Données invalides', error.errors);
    }
    return sendError(res, 400, error.message);
  }
};

export const me = async (req: Request, res: Response, next: NextFunction) => {
  try {
    if (!req.user) {
      return sendError(res, 401, 'Non authentifié');
    }
    const fullProfile = await authService.getUserProfile(req.user.id);
    return sendSuccess(res, 200, 'Profil utilisateur', fullProfile);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};
