import * as residenceMediaRepo from '../repositories/residenceMedia.repository';
import * as residenceProjectsRepo from '../repositories/residenceProjects.repository';
import { createAuditLog } from '../repositories/audit.repository';
import { pool } from '../config/database';

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

export const addMedia = 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 connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    if (data.is_primary) {
      await residenceMediaRepo.resetPrimaryForProject(projectId, connection);
    }

    const mediaId = await residenceMediaRepo.create(projectId, data, connection);

    await createAuditLog({
      user_id: adminId,
      action: 'RESIDENCE_MEDIA_ADDED',
      entity_type: 'RESIDENCE_MEDIA',
      entity_id: mediaId,
      ip_address: ip,
      user_agent: userAgent
    }, connection);

    await connection.commit();
    return { id: mediaId };
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};

export const updateMedia = async (mediaId: number, data: any, adminId: number, ip?: string, userAgent?: string) => {
  const media = await residenceMediaRepo.findById(mediaId);
  if (!media) throw new Error('Média introuvable');

  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    if (data.is_primary) {
      await residenceMediaRepo.resetPrimaryForProject(media.residence_project_id, connection);
    }

    await residenceMediaRepo.update(mediaId, data, connection);

    await createAuditLog({
      user_id: adminId,
      action: 'RESIDENCE_MEDIA_UPDATED',
      entity_type: 'RESIDENCE_MEDIA',
      entity_id: mediaId,
      ip_address: ip,
      user_agent: userAgent
    }, connection);

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

export const deleteMedia = async (mediaId: number, adminId: number, ip?: string, userAgent?: string) => {
  const media = await residenceMediaRepo.findById(mediaId);
  if (!media) throw new Error('Média introuvable');

  await residenceMediaRepo.remove(mediaId);

  await createAuditLog({
    user_id: adminId,
    action: 'RESIDENCE_MEDIA_DELETED',
    entity_type: 'RESIDENCE_MEDIA',
    entity_id: mediaId,
    ip_address: ip,
    user_agent: userAgent
  });
};
