import { Request, Response, NextFunction } from 'express';
import * as propertiesService from '../services/properties.service';
import { sendSuccess, sendError } from '../utils/apiResponse';

export const listPublic = 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,
      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,
      sort: req.query.sort as string,
      order: req.query.order as 'ASC' | 'DESC',
      amenity_ids: req.query.amenity_ids ? (req.query.amenity_ids as string).split(',').map(Number) : undefined,
      ids: req.query.ids ? (req.query.ids as string).split(',').map(Number) : undefined
    };

    const result = await propertiesService.getPublicProperties(filters);
    return sendSuccess(res, 200, 'Liste des biens', result.data, result.pagination);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const getPublicOne = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const property = await propertiesService.getPropertyByIdOrSlug(req.params.slug as string);
    if (!property || property.property_status !== 'AVAILABLE') {
      return sendError(res, 404, 'Bien introuvable ou non disponible');
    }
    return sendSuccess(res, 200, 'Bien immobilier', property);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const getCities = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const cities = await propertiesService.getCities();
    return sendSuccess(res, 200, 'Villes', cities);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const getDistricts = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const city = req.query.city as string | undefined;
    const districts = await propertiesService.getDistricts(city);
    return sendSuccess(res, 200, 'Quartiers', districts);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const getTypes = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const types = await propertiesService.getTypes();
    return sendSuccess(res, 200, 'Typologies', types);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const getFeatured = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const filters = {
      page: 1,
      limit: 10,
      featured: true
    };
    const result = await propertiesService.getPublicProperties(filters);
    return sendSuccess(res, 200, 'Biens mis en avant', result.data, result.pagination);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const getRecent = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const filters = {
      page: 1,
      limit: 12,
      sort: 'published_at',
      order: 'DESC' as 'DESC'
    };
    const result = await propertiesService.getPublicProperties(filters);
    return sendSuccess(res, 200, 'Biens récents', result.data, result.pagination);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const getAmenities = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { getAmenities } = await import('../services/amenities.service');
    const amenities = await getAmenities();
    return sendSuccess(res, 200, 'Liste des équipements', amenities);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};
