import { pool } from '../config/database';
import * as propertiesRepo from '../repositories/properties.repository';
import * as auditRepo from '../repositories/audit.repository';
import * as usersRepo from '../repositories/users.repository';
import slugify from 'slugify';
import * as amenitiesRepo from '../repositories/amenities.repository';
import * as propertyMediaRepo from '../repositories/propertyMedia.repository';

// Générer un slug unique
const generateUniqueSlug = async (title: string, connection?: any): Promise<string> => {
  const baseSlug = slugify(title, { lower: true, strict: true, locale: 'fr' });
  let slug = baseSlug;
  let counter = 1;
  
  while (await propertiesRepo.findBySlug(slug, connection)) {
    counter++;
    slug = `${baseSlug}-${counter}`;
  }
  
  return slug;
};

// Générer une référence unique (FBK-XXXXX)
const generateReference = async (connection?: any): Promise<string> => {
  const db = connection || pool;
  const [rows] = await (db as any).query('SELECT id FROM properties ORDER BY id DESC LIMIT 1');
  const lastId = rows[0]?.id || 0;
  const nextId = lastId + 1;
  return `FBK-${nextId.toString().padStart(5, '0')}`;
};

export const getProperties = async (filters: propertiesRepo.PropertyFilters) => {
  const result = await propertiesRepo.findAll(filters);
  const dataWithMedia = await Promise.all(
    result.data.map(async (prop) => {
      const media = await propertyMediaRepo.findAllByProperty(prop.id);
      return {
        ...prop,
        area: prop.surface || (prop as any).area,
        status: prop.property_status || (prop as any).status,
        media: media.map(m => ({
          ...m,
          file_path: m.url,
          media_type: m.type || 'IMAGE',
          is_primary: Boolean(m.is_primary)
        }))
      };
    })
  );
  return {
    ...result,
    data: dataWithMedia
  };
};

export const getPublicProperties = async (filters: propertiesRepo.PropertyFilters) => {
  const publicFilters = {
    ...filters,
    property_status: 'AVAILABLE'
  };
  return await getProperties(publicFilters);
};

export const getCities = async () => {
  return await propertiesRepo.getDistinctCities();
};

export const getDistricts = async (city?: string) => {
  return await propertiesRepo.getDistinctDistricts(city);
};

export const getTypes = async () => {
  return await propertiesRepo.getDistinctTypes();
};

export const getPropertyByIdOrSlug = async (identifier: string | number, includeRelations: boolean = true) => {
  let property: propertiesRepo.Property | null = null;
  if (typeof identifier === 'number' || !isNaN(Number(identifier))) {
    property = await propertiesRepo.findById(Number(identifier));
  } else {
    property = await propertiesRepo.findBySlug(identifier as string);
  }

  if (!property) return null;

  if (includeRelations) {
    const [amenities, media, similar] = await Promise.all([
      amenitiesRepo.getAmenitiesForProperty(property.id),
      propertyMediaRepo.findAllByProperty(property.id),
      propertiesRepo.findSimilar(property)
    ]);
    const mappedMedia = media.map(m => ({
      ...m,
      file_path: m.url,
      media_type: m.type || 'IMAGE',
      is_primary: Boolean(m.is_primary)
    }));
    return {
      ...property,
      area: property.surface || (property as any).area,
      status: property.property_status || (property as any).status,
      amenities,
      media: mappedMedia,
      similar_properties: similar
    };
  }

  return {
    ...property,
    area: property.surface || (property as any).area,
    status: property.property_status || (property as any).status
  };
};


export const createProperty = async (data: any, userId: number, ip: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    if (data.agent_id) {
      const agent = await usersRepo.findUserById(data.agent_id);
      if (!agent) {
        throw new Error('L\'agent assigné est introuvable');
      }
    }

    const slug = await generateUniqueSlug(data.title, connection);
    const reference = data.reference || await generateReference(connection);

    const propertyData = {
      ...data,
      slug,
      reference,
      property_status: data.property_status || 'DRAFT'
    };

    const propertyId = await propertiesRepo.create(propertyData, connection);

    await auditRepo.createAuditLog({
      user_id: userId,
      action: 'CREATE',
      entity_type: 'PROPERTY',
      entity_id: propertyId,
      old_values: null,
      new_values: propertyData,
      ip_address: ip,
      user_agent: userAgent
    }, connection);

    await connection.commit();
    return { id: propertyId, reference, slug };
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};

export const updateProperty = async (id: number, data: any, userId: number, ip: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const existingProperty = await propertiesRepo.findById(id, connection);
    if (!existingProperty) throw new Error('Bien introuvable');

    if (data.agent_id && data.agent_id !== existingProperty.agent_id) {
      const agent = await usersRepo.findUserById(data.agent_id);
      if (!agent) throw new Error('L\'agent assigné est introuvable');
    }

    let updateData = { ...data };
    
    // Si le titre change, on regénère le slug ? 
    // Généralement non pour le SEO, sauf s'ils le demandent. On ne le change pas par défaut.

    await propertiesRepo.update(id, updateData, connection);

    await auditRepo.createAuditLog({
      user_id: userId,
      action: 'UPDATE',
      entity_type: 'PROPERTY',
      entity_id: id,
      old_values: existingProperty,
      new_values: updateData,
      ip_address: ip,
      user_agent: userAgent
    }, connection);

    await connection.commit();
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};

export const updatePropertyStatus = async (id: number, status: string, userId: number, ip: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const existingProperty = await propertiesRepo.findById(id, connection);
    if (!existingProperty) throw new Error('Bien introuvable');

    await propertiesRepo.update(id, { property_status: status }, connection);

    await auditRepo.createAuditLog({
      user_id: userId,
      action: 'UPDATE_STATUS',
      entity_type: 'PROPERTY',
      entity_id: id,
      old_values: { property_status: existingProperty.property_status },
      new_values: { property_status: status },
      ip_address: ip,
      user_agent: userAgent
    }, connection);

    await connection.commit();
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};

export const publishProperty = async (id: number, isPublished: boolean, userId: number, ip: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const existingProperty = await propertiesRepo.findById(id, connection);
    if (!existingProperty) throw new Error('Bien introuvable');

    const updateData: any = {};
    if (isPublished) {
      updateData.property_status = 'AVAILABLE';
      updateData.published_at = new Date().toISOString().slice(0, 19).replace('T', ' '); // Format MySQL
    } else {
      updateData.property_status = 'DRAFT';
      updateData.published_at = null;
    }

    await propertiesRepo.update(id, updateData, connection);

    await auditRepo.createAuditLog({
      user_id: userId,
      action: isPublished ? 'PUBLISH' : 'UNPUBLISH',
      entity_type: 'PROPERTY',
      entity_id: id,
      old_values: { property_status: existingProperty.property_status, published_at: existingProperty.published_at },
      new_values: updateData,
      ip_address: ip,
      user_agent: userAgent
    }, connection);

    await connection.commit();
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};

export const featureProperty = async (id: number, featured: boolean, userId: number, ip: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const existingProperty = await propertiesRepo.findById(id, connection);
    if (!existingProperty) throw new Error('Bien introuvable');

    await propertiesRepo.update(id, { featured: featured }, connection);

    await auditRepo.createAuditLog({
      user_id: userId,
      action: 'UPDATE_FEATURED',
      entity_type: 'PROPERTY',
      entity_id: id,
      old_values: { featured: existingProperty.featured },
      new_values: { featured: featured },
      ip_address: ip,
      user_agent: userAgent
    }, connection);

    await connection.commit();
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};

export const deleteProperty = async (id: number, userId: number, ip: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const existingProperty = await propertiesRepo.findById(id, connection);
    if (!existingProperty) throw new Error('Bien introuvable');

    await propertiesRepo.deleteById(id, connection);

    await auditRepo.createAuditLog({
      user_id: userId,
      action: 'DELETE',
      entity_type: 'PROPERTY',
      entity_id: id,
      old_values: existingProperty,
      new_values: null,
      ip_address: ip,
      user_agent: userAgent
    }, connection);

    await connection.commit();
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};
