import { Request, Response, NextFunction } from 'express';
import * as propertiesService from '../services/properties.service';
import { createPropertySchema, updatePropertySchema, updatePropertyStatusSchema, updatePropertyPublishSchema, updatePropertyFeatureSchema } from '../validators/properties.validator';
import { sendSuccess, sendError } from '../utils/apiResponse';

export const list = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const filters = {
      page: req.query.page ? parseInt(req.query.page as string) : 1,
      limit: req.query.limit ? parseInt(req.query.limit as string) : 20,
      search: req.query.search as string,
      transaction_type: req.query.transaction_type as string,
      property_type: req.query.property_type as string,
      property_status: req.query.property_status as string,
      city: req.query.city as string,
      commune: req.query.commune as string,
      district: req.query.district as string,
      min_price: req.query.min_price ? parseFloat(req.query.min_price as string) : undefined,
      max_price: req.query.max_price ? parseFloat(req.query.max_price as string) : undefined,
      min_surface: req.query.min_surface ? parseFloat(req.query.min_surface as string) : undefined,
      max_surface: req.query.max_surface ? parseFloat(req.query.max_surface as string) : undefined,
      rooms: req.query.rooms ? parseInt(req.query.rooms as string) : undefined,
      bedrooms: req.query.bedrooms ? parseInt(req.query.bedrooms as string) : undefined,
      bathrooms: req.query.bathrooms ? parseInt(req.query.bathrooms as string) : undefined,
      furnished: req.query.furnished !== undefined ? req.query.furnished === 'true' : undefined,
      featured: req.query.featured !== undefined ? req.query.featured === 'true' : undefined,
      category: req.query.category as string,
      is_colocation: req.query.is_colocation !== undefined ? req.query.is_colocation === 'true' : undefined,
      is_budget_friendly: req.query.is_budget_friendly !== undefined ? req.query.is_budget_friendly === 'true' : undefined,
      agent_id: req.query.agent_id ? parseInt(req.query.agent_id as string) : undefined,
      sort: req.query.sort as string,
      order: req.query.order as 'ASC' | 'DESC'
    };

    const result = await propertiesService.getProperties(filters);
    return sendSuccess(res, 200, 'Liste des biens', result.data, result.pagination);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const getOne = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const property = await propertiesService.getPropertyByIdOrSlug(req.params.id as string);
    if (!property) return sendError(res, 404, 'Bien introuvable');
    return sendSuccess(res, 200, 'Bien immobilier', property);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const create = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const validated = createPropertySchema.parse(req);
    const result = await propertiesService.createProperty(validated.body, req.user!.id, req.ip || '', req.headers['user-agent'] as unknown as string | undefined);
    return sendSuccess(res, 201, 'Bien créé 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 update = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = parseInt(req.params.id as string);
    const validated = updatePropertySchema.parse(req);
    await propertiesService.updateProperty(id, validated.body, req.user!.id, req.ip || '', req.headers['user-agent'] as unknown as string | undefined);
    return sendSuccess(res, 200, 'Bien mis à jour 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 updateStatus = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = parseInt(req.params.id as string);
    const validated = updatePropertyStatusSchema.parse(req);
    await propertiesService.updatePropertyStatus(id, validated.body.status, req.user!.id, req.ip || '', req.headers['user-agent'] as unknown as string | undefined);
    return sendSuccess(res, 200, 'Statut du bien 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 publish = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = parseInt(req.params.id as string);
    const validated = updatePropertyPublishSchema.parse(req);
    await propertiesService.publishProperty(id, validated.body.is_published, req.user!.id, req.ip || '', req.headers['user-agent'] as unknown as string | undefined);
    return sendSuccess(res, 200, validated.body.is_published ? 'Bien publié' : 'Bien dépublié');
  } catch (error: any) {
    if (error.name === 'ZodError') return sendError(res, 400, 'Données invalides', error.errors);
    return sendError(res, 400, error.message);
  }
};

export const feature = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = parseInt(req.params.id as string);
    const validated = updatePropertyFeatureSchema.parse(req);
    await propertiesService.featureProperty(id, validated.body.featured, req.user!.id, req.ip || '', req.headers['user-agent'] as unknown as string | undefined);
    return sendSuccess(res, 200, 'Mise en avant mise à 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 remove = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = parseInt(req.params.id as string);
    await propertiesService.deleteProperty(id, req.user!.id, req.ip || '', req.headers['user-agent'] as unknown as string | undefined);
    return sendSuccess(res, 200, 'Bien supprimé avec succès');
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};
