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

export const getAllProjects = async () => {
  return residenceProjectsRepo.findAll();
};

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

export const createProject = async (data: any, adminId: number, ip?: string, userAgent?: string) => {
  const existing = await residenceProjectsRepo.findBySlug(data.slug);
  if (existing) {
    throw new Error('Un projet avec ce slug existe déjà');
  }

  const projectId = await residenceProjectsRepo.create(data);

  await createAuditLog({
    user_id: adminId,
    action: 'RESIDENCE_CREATED',
    entity_type: 'RESIDENCE_PROJECT',
    entity_id: projectId,
    ip_address: ip,
    user_agent: userAgent
  });

  return { id: projectId };
};

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

  if (data.slug && data.slug !== project.slug) {
    const existing = await residenceProjectsRepo.findBySlug(data.slug);
    if (existing) throw new Error('Un projet avec ce slug existe déjà');
  }

  await residenceProjectsRepo.update(id, data);

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

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

  await residenceProjectsRepo.remove(id);

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