import { Request, Response, NextFunction } from 'express';
import * as residenceProjectsService from '../services/residenceProjects.service';
import { sendSuccess, sendError } from '../utils/apiResponse';
import { createResidenceProjectSchema, updateResidenceProjectSchema } from '../validators/residence.validator';
import { processAndSaveWebp } from '../middlewares/upload.middleware';

export const list = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const projects = await residenceProjectsService.getAllProjects();
    return sendSuccess(res, 200, 'Liste des projets', projects);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const getOne = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const project = await residenceProjectsService.getProjectById(parseInt(req.params.id as string));
    if (!project) return sendError(res, 404, 'Projet introuvable');
    return sendSuccess(res, 200, 'Détail projet', project);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const create = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const validated = createResidenceProjectSchema.parse(req);
    
    if (req.file) {
      const { url } = await processAndSaveWebp(req.file.path || req.file.buffer, 'residence');
      validated.body.cover_image = url;
    }
    
    const result = await residenceProjectsService.createProject(validated.body, req.user!.id, req.ip, req.headers['user-agent'] as unknown as string | undefined | undefined);
    return sendSuccess(res, 201, 'Projet créé', result);
  } catch (error: any) {
    if (error.name === 'ZodError') {
      console.error('ZodError in create:', error.errors);
      return sendError(res, 400, 'Données invalides', error.errors);
    }
    return sendError(res, 400, error.message);
  }
};

export const update = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const validated = updateResidenceProjectSchema.parse(req);
    
    if (req.file) {
      const { url } = await processAndSaveWebp(req.file.path || req.file.buffer, 'residence');
      validated.body.cover_image = url;
    }
    
    await residenceProjectsService.updateProject(parseInt(req.params.id as string), validated.body, req.user!.id, req.ip, req.headers['user-agent'] as unknown as string | undefined | undefined);
    return sendSuccess(res, 200, 'Projet mis à jour');
  } catch (error: any) {
    if (error.name === 'ZodError') {
      console.error('ZodError in update:', error.errors);
      return sendError(res, 400, 'Données invalides', error.errors);
    }
    return sendError(res, 400, error.message);
  }
};

export const remove = async (req: Request, res: Response, next: NextFunction) => {
  try {
    await residenceProjectsService.deleteProject(parseInt(req.params.id as string), req.user!.id, req.ip, req.headers['user-agent'] as unknown as string | undefined | undefined);
    return sendSuccess(res, 200, 'Projet supprimé');
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const uploadBrochure = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const projectId = parseInt(req.params.id as string);
    if (!req.file) {
      return sendError(res, 400, 'Aucun fichier PDF fourni pour la brochure');
    }

    const fileUrl = `/uploads/documents/${req.file.filename}`;
    await residenceProjectsService.updateProject(
      projectId, 
      { brochure_url: fileUrl }, 
      req.user!.id, 
      req.ip, 
      req.headers['user-agent'] as unknown as string | undefined
    );

    return sendSuccess(res, 200, 'Brochure mise à jour avec succès', {
      brochure_url: fileUrl,
      filename: req.file.originalname
    });
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const uploadPlans = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const projectId = parseInt(req.params.id as string);
    if (!req.file) {
      return sendError(res, 400, 'Aucun fichier PDF fourni pour les plans');
    }

    const fileUrl = `/uploads/documents/${req.file.filename}`;
    await residenceProjectsService.updateProject(
      projectId, 
      { architectural_plan_url: fileUrl }, 
      req.user!.id, 
      req.ip, 
      req.headers['user-agent'] as unknown as string | undefined
    );

    return sendSuccess(res, 200, 'Plans architecturaux mis à jour avec succès', {
      architectural_plan_url: fileUrl,
      filename: req.file.originalname
    });
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

