import * as residenceUnitTypesRepo from '../repositories/residenceUnitTypes.repository';
import * as residenceProjectsRepo from '../repositories/residenceProjects.repository';
import { createAuditLog } from '../repositories/audit.repository';

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

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

export const createUnitType = 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 existing = await residenceUnitTypesRepo.findByCode(projectId, data.code);
  if (existing) {
    throw new Error('Une typologie avec ce code existe déjà pour ce projet');
  }

  const typeId = await residenceUnitTypesRepo.create(projectId, data);

  await createAuditLog({
    user_id: adminId,
    action: 'UNIT_TYPE_CREATED',
    entity_type: 'RESIDENCE_UNIT_TYPE',
    entity_id: typeId,
    ip_address: ip,
    user_agent: userAgent
  });

  return { id: typeId };
};

export const updateUnitType = async (id: number, data: any, adminId: number, ip?: string, userAgent?: string) => {
  const unitType = await residenceUnitTypesRepo.findById(id);
  if (!unitType) throw new Error('Typologie introuvable');

  if (data.code && data.code !== unitType.code) {
    const existing = await residenceUnitTypesRepo.findByCode(unitType.residence_project_id, data.code);
    if (existing) throw new Error('Une typologie avec ce code existe déjà pour ce projet');
  }

  await residenceUnitTypesRepo.update(id, data);

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

export const deleteUnitType = async (id: number, adminId: number, ip?: string, userAgent?: string) => {
  const unitType = await residenceUnitTypesRepo.findById(id);
  if (!unitType) throw new Error('Typologie introuvable');

  await residenceUnitTypesRepo.remove(id);

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