import { Request, Response, NextFunction } from 'express';
import * as visitsService from '../services/visits.service';
import { createVisitSlotSchema, updateVisitSlotSchema, updateVisitSlotStatusSchema, createVisitRequestSchema, updateVisitRequestStatusSchema, assignVisitRequestSchema, addNoteVisitRequestSchema } from '../validators/visits.validator';
import { sendSuccess, sendError } from '../utils/apiResponse';

// ==============================
// SLOTS
// ==============================

export const listAllSlots = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const slots = await visitsService.getAllVisitSlots();
    return sendSuccess(res, 200, 'Tous les créneaux de visite', slots);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const listSlotsForProperty = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const propertyId = parseInt(req.params.propertyId as string);
    const slots = await visitsService.getVisitSlotsForProperty(propertyId, true);
    return sendSuccess(res, 200, 'Créneaux de visite', slots);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const listAvailableSlotsForProperty = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const propertyId = parseInt(req.params.propertyId as string);
    const slots = await visitsService.getVisitSlotsForProperty(propertyId, true);
    return sendSuccess(res, 200, 'Créneaux de visite disponibles', slots);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const createSlot = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const validated = createVisitSlotSchema.parse(req);
    const propertyId = req.params.propertyId ? parseInt(req.params.propertyId as string) : validated.body.property_id;
    if (!propertyId) throw new Error('ID du bien immobilier requis');

    const result = await visitsService.createVisitSlot(propertyId, validated.body, req.user!.id, req.ip || '', req.headers['user-agent'] as unknown as string | undefined);
    return sendSuccess(res, 201, 'Créneau créé', 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 generateBatchSlots = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { property_id, start_date, weeks, schedules } = req.body;
    if (!property_id) throw new Error('ID du bien immobilier requis');
    if (!start_date) throw new Error('Date de début requise');

    const targetPropertyId = (property_id === 'ALL' || property_id === 'all') ? 'ALL' : parseInt(property_id);

    const result = await visitsService.generateWeekdaysVisitSlots(
      targetPropertyId,
      start_date,
      parseInt(weeks || 2),
      req.user!.id,
      req.ip || '',
      req.headers['user-agent'] as unknown as string | undefined,
      schedules
    );
    return sendSuccess(res, 201, `${result.createdCount} créneau(x) généré(s) avec succès`, result);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const updateSlot = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = parseInt(req.params.id as string);
    const validated = updateVisitSlotSchema.parse(req);
    await visitsService.updateVisitSlot(id, validated.body, req.user!.id, req.ip || '', req.headers['user-agent'] as unknown as string | undefined);
    return sendSuccess(res, 200, 'Créneau mis à jour');
  } catch (error: any) {
    if (error.name === 'ZodError') return sendError(res, 400, 'Données invalides', error.errors);
    return sendError(res, 400, error.message);
  }
};

export const updateSlotStatus = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = parseInt(req.params.id as string);
    const validated = updateVisitSlotStatusSchema.parse(req);
    await visitsService.updateVisitSlotStatus(id, validated.body.status, req.user!.id, req.ip || '', req.headers['user-agent'] as unknown as string | undefined);
    return sendSuccess(res, 200, 'Statut du créneau mis à jour');
  } catch (error: any) {
    if (error.name === 'ZodError') return sendError(res, 400, 'Données invalides', error.errors);
    return sendError(res, 400, error.message);
  }
};

export const deleteSlot = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = parseInt(req.params.id as string);
    await visitsService.deleteVisitSlot(id, req.user!.id, req.ip || '', req.headers['user-agent'] as unknown as string | undefined);
    return sendSuccess(res, 200, 'Créneau supprimé');
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

// ==============================
// REQUESTS
// ==============================

export const listRequests = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const requests = await visitsService.getVisitRequests();
    return sendSuccess(res, 200, 'Demandes de visite', requests);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const getRequest = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = parseInt(req.params.id as string);
    const request = await visitsService.getVisitRequestById(id);
    if (!request) return sendError(res, 404, 'Demande introuvable');
    return sendSuccess(res, 200, 'Détail de la demande', request);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const createRequestPublic = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const validated = createVisitRequestSchema.parse(req);
    // Public endpoint: req.user could be populated if they pass token, but it's optional
    const userId = req.user?.id || null;
    const result = await visitsService.createVisitRequest(validated.body, userId, req.ip || '', req.headers['user-agent'] as unknown as string | undefined);
    return sendSuccess(res, 201, 'Demande envoyée avec succès', 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 updateRequestStatus = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = parseInt(req.params.id as string);
    const validated = updateVisitRequestStatusSchema.parse(req);
    await visitsService.updateVisitRequestStatus(id, validated.body.status, req.user!.id, req.ip || '', req.headers['user-agent'] as unknown as string | undefined);
    return sendSuccess(res, 200, 'Statut de la demande mis à jour');
  } catch (error: any) {
    if (error.name === 'ZodError') return sendError(res, 400, 'Données invalides', error.errors);
    return sendError(res, 400, error.message);
  }
};

export const assignRequest = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = parseInt(req.params.id as string);
    const validated = assignVisitRequestSchema.parse(req);
    await visitsService.assignVisitRequest(id, validated.body.assigned_agent_id, req.user!.id, req.ip || '', req.headers['user-agent'] as unknown as string | undefined);
    return sendSuccess(res, 200, 'Agent assigné à la demande');
  } catch (error: any) {
    if (error.name === 'ZodError') return sendError(res, 400, 'Données invalides', error.errors);
    return sendError(res, 400, error.message);
  }
};

export const addRequestNote = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = parseInt(req.params.id as string);
    const validated = addNoteVisitRequestSchema.parse(req);
    await visitsService.addNoteToVisitRequest(id, validated.body.admin_notes || null, req.user!.id, req.ip || '', req.headers['user-agent'] as unknown as string | undefined);
    return sendSuccess(res, 200, 'Note ajoutée');
  } catch (error: any) {
    if (error.name === 'ZodError') return sendError(res, 400, 'Données invalides', error.errors);
    return sendError(res, 400, error.message);
  }
};
