import type { Request, Response, NextFunction } from 'express';
import * as clientInvitationService from '../services/client-invitations.service.js';
import { hasAnyPlatformRole } from '../utils/platform-admin.js';

export async function createInvitation(req: Request, res: Response, next: NextFunction) {
  try {
    const { email, nombreDespacho, rfc } = req.body;
    if (!email) {
      return res.status(400).json({ message: 'El email es requerido' });
    }

    // Solo platform_admin puede crear invitaciones de cliente
    const isAdmin = await hasAnyPlatformRole(req.user!.userId, 'platform_admin');
    if (!isAdmin) {
      return res.status(403).json({ message: 'Solo administradores pueden crear invitaciones' });
    }

    const invitation = await clientInvitationService.createInvitation({
      email,
      invitedBy: req.user!.userId,
      invitedByName: (req.user as any)?.nombre || 'Horux Despachos',
      nombreDespacho,
      rfc,
    });

    res.status(201).json({ message: 'Invitación enviada', invitation });
  } catch (error: any) {
    res.status(400).json({ message: error.message });
  }
}

export async function validateToken(req: Request, res: Response, next: NextFunction) {
  try {
    const token = String(req.params.token);
    const invitation = await clientInvitationService.validateInvitationToken(token);
    res.json({
      email: invitation.email,
      nombreDespacho: invitation.nombreDespacho,
      rfc: invitation.rfc,
      expiresAt: invitation.expiresAt,
    });
  } catch (error: any) {
    res.status(400).json({ message: error.message });
  }
}

export async function registerFromInvitation(req: Request, res: Response, next: NextFunction) {
  try {
    const token = String(req.params.token);
    const { nombre, password, nombreDespacho, rfc, verticalProfile, codigoPostal } = req.body;

    if (!nombre || !password || !nombreDespacho || !rfc || !verticalProfile) {
      return res.status(400).json({ message: 'Todos los campos son requeridos' });
    }

    const result = await clientInvitationService.registerFromInvitation(token, {
      nombre,
      password,
      nombreDespacho,
      rfc,
      verticalProfile,
      codigoPostal,
    });

    res.status(201).json(result);
  } catch (error: any) {
    res.status(400).json({ message: error.message });
  }
}

export async function resendInvitation(req: Request, res: Response, next: NextFunction) {
  try {
    const isAdmin = await hasAnyPlatformRole(req.user!.userId, 'platform_admin');
    if (!isAdmin) {
      return res.status(403).json({ message: 'No autorizado' });
    }

    const id = String(req.params.id);
    const result = await clientInvitationService.resendInvitation(
      id,
      (req.user as any)?.nombre || 'Horux Despachos'
    );
    res.json(result);
  } catch (error: any) {
    res.status(400).json({ message: error.message });
  }
}

export async function listInvitations(req: Request, res: Response, next: NextFunction) {
  try {
    const isAdmin = await hasAnyPlatformRole(req.user!.userId, 'platform_admin');
    if (!isAdmin) {
      return res.status(403).json({ message: 'No autorizado' });
    }

    const invitations = await clientInvitationService.listInvitations();
    res.json(invitations);
  } catch (error: any) {
    next(error);
  }
}
