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

// --- MILESTONES ---

export const getMilestones = async (projectId: number) => {
  return constructionRepo.findMilestonesByProject(projectId);
};

export const createMilestone = 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 id = await constructionRepo.createMilestone(projectId, data);
  await createAuditLog({
    user_id: adminId, action: 'CONSTRUCTION_CREATED', entity_type: 'MILESTONE', entity_id: id, ip_address: ip, user_agent: userAgent
  });
  return { id };
};

export const updateMilestone = async (id: number, data: any, adminId: number, ip?: string, userAgent?: string) => {
  const milestone = await constructionRepo.findMilestoneById(id);
  if (!milestone) throw new Error('Étape introuvable');

  if (data.status === 'VALIDATED' && milestone.status !== 'VALIDATED') {
    data.validation_date = new Date();
    data.validated_by = adminId;
  }

  await constructionRepo.updateMilestone(id, data);
  await createAuditLog({
    user_id: adminId, action: data.status === 'VALIDATED' ? 'CONSTRUCTION_VALIDATED' : 'CONSTRUCTION_UPDATED',
    entity_type: 'MILESTONE', entity_id: id, ip_address: ip, user_agent: userAgent
  });
};

export const deleteMilestone = async (id: number, adminId: number, ip?: string, userAgent?: string) => {
  const milestone = await constructionRepo.findMilestoneById(id);
  if (!milestone) throw new Error('Étape introuvable');

  await constructionRepo.removeMilestone(id);
};

// --- MILESTONE PHOTOS ---

export const getMilestonePhotos = async (milestoneId: number) => {
  return constructionRepo.findPhotosByMilestone(milestoneId);
};

export const createMilestonePhoto = async (milestoneId: number, data: { file_url: string; caption?: string }, adminId: number) => {
  const milestone = await constructionRepo.findMilestoneById(milestoneId);
  if (!milestone) throw new Error('Étape introuvable');
  
  const photoId = await constructionRepo.addMilestonePhoto(milestoneId, data.file_url, data.caption);
  await createAuditLog({
    user_id: adminId, action: 'CONSTRUCTION_PHOTO_ADDED', entity_type: 'MILESTONE', entity_id: photoId
  });
  return { id: photoId, file_url: data.file_url, caption: data.caption };
};

export const deleteMilestonePhoto = async (photoId: number, adminId: number) => {
  await constructionRepo.deleteMilestonePhoto(photoId);
  await createAuditLog({
    user_id: adminId, action: 'CONSTRUCTION_PHOTO_DELETED', entity_type: 'MILESTONE_PHOTO', entity_id: photoId
  });
};

// --- UPDATES ---

export const getUpdates = async (projectId: number, isPublic: boolean) => {
  return constructionRepo.findUpdatesByProject(projectId, isPublic);
};

export const getUpdateByIdOrSlug = async (identifier: string) => {
  const isId = /^\d+$/.test(identifier);
  if (isId) return constructionRepo.findUpdateById(parseInt(identifier));
  return constructionRepo.findUpdateBySlug(identifier);
};

export const createUpdate = async (projectId: number, data: any, adminId: number, ip?: string, userAgent?: string) => {
  data.author_id = adminId;
  const id = await constructionRepo.createUpdate(projectId, data);
  await createAuditLog({
    user_id: adminId, action: 'CONSTRUCTION_CREATED', entity_type: 'UPDATE', entity_id: id, ip_address: ip, user_agent: userAgent
  });
  return { id };
};

export const modifyUpdate = async (id: number, data: any, adminId: number, ip?: string, userAgent?: string) => {
  const update = await constructionRepo.findUpdateById(id);
  if (!update) throw new Error('Actualité introuvable');

  if (data.status === 'PUBLISHED' && update.status !== 'PUBLISHED') {
    data.published_at = new Date();
  } else if (data.status === 'DRAFT' && update.status !== 'DRAFT') {
    data.published_at = null;
  }

  await constructionRepo.updateUpdate(id, data);
  await createAuditLog({
    user_id: adminId, action: data.status === 'PUBLISHED' ? 'CONSTRUCTION_PUBLISHED' : 'CONSTRUCTION_UPDATED',
    entity_type: 'UPDATE', entity_id: id, ip_address: ip, user_agent: userAgent
  });
};

export const deleteUpdate = async (id: number) => {
  await constructionRepo.removeUpdate(id);
};

// --- PHOTOS ---

export const getPhotos = async (updateId: number) => {
  return constructionRepo.findPhotosByUpdate(updateId);
};

export const addPhoto = async (updateId: number, data: any) => {
  const update = await constructionRepo.findUpdateById(updateId);
  if (!update) throw new Error('Actualité introuvable');
  const id = await constructionRepo.createPhoto(updateId, data);
  return { id };
};

export const deletePhoto = async (id: number) => {
  await constructionRepo.removePhoto(id);
};
