import { pool } from '../config/database';
import * as amenitiesRepo from '../repositories/amenities.repository';
import * as auditRepo from '../repositories/audit.repository';
import * as propertiesRepo from '../repositories/properties.repository';

export const getAmenities = async () => {
  return await amenitiesRepo.findAll();
};

export const createAmenity = async (name: string, icon: string | null, userId: number, ip: string, userAgent?: string) => {
  const existing = await amenitiesRepo.findByName(name);
  if (existing) throw new Error('Un équipement avec ce nom existe déjà');

  const id = await amenitiesRepo.create(name, icon);
  
  await auditRepo.createAuditLog({
    user_id: userId,
    action: 'CREATE',
    entity_type: 'AMENITY',
    entity_id: id,
    old_values: null,
    new_values: { name, icon },
    ip_address: ip,
    user_agent: userAgent
  });
  
  return { id, name, icon };
};

export const updateAmenity = async (id: number, data: { name?: string, icon?: string | null }, userId: number, ip: string, userAgent?: string) => {
  const existing = await amenitiesRepo.findById(id);
  if (!existing) throw new Error('Équipement introuvable');

  if (data.name && data.name !== existing.name) {
    const nameCheck = await amenitiesRepo.findByName(data.name);
    if (nameCheck) throw new Error('Un équipement avec ce nom existe déjà');
  }

  await amenitiesRepo.update(id, data.name, data.icon);
  
  await auditRepo.createAuditLog({
    user_id: userId,
    action: 'UPDATE',
    entity_type: 'AMENITY',
    entity_id: id,
    old_values: existing,
    new_values: { ...existing, ...data },
    ip_address: ip,
    user_agent: userAgent
  });
};

export const deleteAmenity = async (id: number, userId: number, ip: string, userAgent?: string) => {
  const existing = await amenitiesRepo.findById(id);
  if (!existing) throw new Error('Équipement introuvable');

  await amenitiesRepo.deleteById(id);
  
  await auditRepo.createAuditLog({
    user_id: userId,
    action: 'DELETE',
    entity_type: 'AMENITY',
    entity_id: id,
    old_values: existing,
    new_values: null,
    ip_address: ip,
    user_agent: userAgent
  });
};

// ==========================================
// Property Amenities
// ==========================================

export const getPropertyAmenities = async (propertyId: number) => {
  const property = await propertiesRepo.findById(propertyId);
  if (!property) throw new Error('Bien introuvable');
  return await amenitiesRepo.getAmenitiesForProperty(propertyId);
};

export const addAmenityToProperty = async (propertyId: number, amenityId: number, userId: number, ip: string, userAgent?: string) => {
  const property = await propertiesRepo.findById(propertyId);
  if (!property) throw new Error('Bien introuvable');
  
  const amenity = await amenitiesRepo.findById(amenityId);
  if (!amenity) throw new Error('Équipement introuvable');

  const exists = await amenitiesRepo.checkPropertyAmenity(propertyId, amenityId);
  if (exists) return; // Déjà ajouté

  await amenitiesRepo.addPropertyAmenity(propertyId, amenityId);
  
  await auditRepo.createAuditLog({
    user_id: userId,
    action: 'ADD_AMENITY',
    entity_type: 'PROPERTY',
    entity_id: propertyId,
    old_values: null,
    new_values: { amenity_id: amenityId, amenity_name: amenity.name },
    ip_address: ip,
    user_agent: userAgent
  });
};

export const setPropertyAmenities = async (propertyId: number, amenityIds: number[], userId: number, ip: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const property = await propertiesRepo.findById(propertyId, connection);
    if (!property) throw new Error('Bien introuvable');

    const currentAmenities = await amenitiesRepo.getAmenitiesForProperty(propertyId);
    
    await amenitiesRepo.removeAllPropertyAmenities(propertyId, connection);
    
    for (const amenityId of amenityIds) {
      const amenity = await amenitiesRepo.findById(amenityId, connection);
      if (!amenity) throw new Error(`Équipement ${amenityId} introuvable`);
      await amenitiesRepo.addPropertyAmenity(propertyId, amenityId, connection);
    }

    await auditRepo.createAuditLog({
      user_id: userId,
      action: 'SET_AMENITIES',
      entity_type: 'PROPERTY',
      entity_id: propertyId,
      old_values: { amenities: currentAmenities.map(a => a.id) },
      new_values: { amenities: amenityIds },
      ip_address: ip,
      user_agent: userAgent
    }, connection);

    await connection.commit();
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};

export const removeAmenityFromProperty = async (propertyId: number, amenityId: number, userId: number, ip: string, userAgent?: string) => {
  const property = await propertiesRepo.findById(propertyId);
  if (!property) throw new Error('Bien introuvable');

  const amenity = await amenitiesRepo.findById(amenityId);
  if (!amenity) throw new Error('Équipement introuvable');

  await amenitiesRepo.removePropertyAmenity(propertyId, amenityId);
  
  await auditRepo.createAuditLog({
    user_id: userId,
    action: 'REMOVE_AMENITY',
    entity_type: 'PROPERTY',
    entity_id: propertyId,
    old_values: { amenity_id: amenityId, amenity_name: amenity.name },
    new_values: null,
    ip_address: ip,
    user_agent: userAgent
  });
};
