import * as residenceUnitsRepo from '../repositories/residenceUnits.repository';
import * as residenceProjectsRepo from '../repositories/residenceProjects.repository';
import * as residenceUnitTypesRepo from '../repositories/residenceUnitTypes.repository';
import { createAuditLog } from '../repositories/audit.repository';
import { pool } from '../config/database';

export const getUnitsByProject = async (projectId: number) => {
  const project = await residenceProjectsRepo.findById(projectId);
  if (!project) throw new Error('Projet introuvable');
  return residenceUnitsRepo.findAllByProject(projectId);
};

export const getUnitById = async (id: number) => {
  return residenceUnitsRepo.findById(id);
};

export const createUnit = async (projectId: number, data: any, adminId: number, ip?: string, userAgent?: string) => {
  const project = await residenceProjectsRepo.findById(projectId);
  if (!project) throw new Error('Projet introuvable');

  const unitType = await residenceUnitTypesRepo.findById(data.unit_type_id);
  if (!unitType || unitType.residence_project_id !== projectId) {
    throw new Error('Typologie invalide pour ce projet');
  }

  const existing = await residenceUnitsRepo.findByReference(data.reference);
  if (existing) {
    throw new Error('Un lot avec cette référence existe déjà');
  }

  const unitId = await residenceUnitsRepo.create(projectId, data);

  await createAuditLog({
    user_id: adminId,
    action: 'UNIT_CREATED',
    entity_type: 'RESIDENCE_UNIT',
    entity_id: unitId,
    ip_address: ip,
    user_agent: userAgent
  });

  return { id: unitId };
};

export const updateUnit = async (id: number, data: any, adminId: number, ip?: string, userAgent?: string) => {
  const unit = await residenceUnitsRepo.findById(id);
  if (!unit) throw new Error('Lot introuvable');

  if (data.reference && data.reference !== unit.reference) {
    const existing = await residenceUnitsRepo.findByReference(data.reference);
    if (existing) throw new Error('Un lot avec cette référence existe déjà');
  }

  if (data.unit_type_id && data.unit_type_id !== unit.unit_type_id) {
    const unitType = await residenceUnitTypesRepo.findById(data.unit_type_id);
    if (!unitType || unitType.residence_project_id !== unit.residence_project_id) {
      throw new Error('Typologie invalide pour ce projet');
    }
  }

  // Interdire la modification du statut via l'update générique si c'est sensible, mais on autorise avec un droit manage.
  await residenceUnitsRepo.update(id, data);

  await createAuditLog({
    user_id: adminId,
    action: 'UNIT_UPDATED',
    entity_type: 'RESIDENCE_UNIT',
    entity_id: id,
    ip_address: ip,
    user_agent: userAgent
  });
};

export const updateUnitStatus = async (id: number, newStatus: string, adminId: number, ip?: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const unit = await residenceUnitsRepo.findByIdForUpdate(id, connection);
    if (!unit) {
      throw new Error('Lot introuvable');
    }

    if (unit.status === 'SOLD' && newStatus !== 'SOLD') {
      // Pour annuler une vente, il faudrait annuler les acquéreurs, les paiements, etc.
      // C'est une action métier complexe, bloquée par défaut.
      throw new Error('Impossible de changer le statut d\'un lot vendu vers ' + newStatus);
    }

    const updateData: any = { status: newStatus };
    if (newStatus === 'RESERVED' && unit.status !== 'RESERVED') {
      updateData.reserved_at = new Date();
    } else if (newStatus === 'SOLD' && unit.status !== 'SOLD') {
      updateData.sold_at = new Date();
    }

    await residenceUnitsRepo.update(id, updateData, connection);

    await createAuditLog({
      user_id: adminId,
      action: 'UNIT_STATUS_CHANGED',
      entity_type: 'RESIDENCE_UNIT',
      entity_id: id,
      ip_address: ip,
      user_agent: userAgent
    }, connection);

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

export const deleteUnit = async (id: number, adminId: number, ip?: string, userAgent?: string) => {
  const unit = await residenceUnitsRepo.findById(id);
  if (!unit) throw new Error('Lot introuvable');
  
  if (unit.status !== 'AVAILABLE') {
    throw new Error('Seuls les lots disponibles peuvent être supprimés');
  }

  await residenceUnitsRepo.remove(id);

  await createAuditLog({
    user_id: adminId,
    action: 'UNIT_DELETED',
    entity_type: 'RESIDENCE_UNIT',
    entity_id: id,
    ip_address: ip,
    user_agent: userAgent
  });
};
