import { pool } from '../config/database';
import * as propertyMediaRepo from '../repositories/propertyMedia.repository';
import * as propertiesRepo from '../repositories/properties.repository';
import * as auditRepo from '../repositories/audit.repository';

export const getMediaForProperty = async (propertyId: number) => {
  return await propertyMediaRepo.findAllByProperty(propertyId);
};

export const addMedia = async (propertyId: number, data: any, userId: number, ip: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const property = await propertiesRepo.findById(propertyId, connection);
    if (!property) throw new Error('Bien introuvable');

    if (data.is_primary && data.type === 'IMAGE') {
      await propertyMediaRepo.resetPrimaryForProperty(propertyId, connection);
    } else {
      data.is_primary = false;
    }

    const mediaId = await propertyMediaRepo.create(propertyId, data, connection);

    await auditRepo.createAuditLog({
      user_id: userId,
      action: 'ADD_MEDIA',
      entity_type: 'PROPERTY',
      entity_id: propertyId,
      old_values: null,
      new_values: { media_id: mediaId, url: data.url, type: data.type },
      ip_address: ip,
      user_agent: userAgent
    }, connection);

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

export const updateMedia = async (mediaId: number, data: any, userId: number, ip: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const existingMedia = await propertyMediaRepo.findById(mediaId, connection);
    if (!existingMedia) throw new Error('Média introuvable');

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

    await auditRepo.createAuditLog({
      user_id: userId,
      action: 'UPDATE_MEDIA',
      entity_type: 'PROPERTY',
      entity_id: existingMedia.property_id,
      old_values: { media_id: mediaId, sort_order: existingMedia.sort_order, alt_text: existingMedia.alt_text },
      new_values: { media_id: mediaId, sort_order: data.sort_order, alt_text: data.alt_text },
      ip_address: ip,
      user_agent: userAgent
    }, connection);

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

export const setPrimaryMedia = async (mediaId: number, userId: number, ip: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const existingMedia = await propertyMediaRepo.findById(mediaId, connection);
    if (!existingMedia) throw new Error('Média introuvable');
    if (existingMedia.type !== 'IMAGE') throw new Error('Seule une image peut être principale');

    await propertyMediaRepo.resetPrimaryForProperty(existingMedia.property_id, connection);
    await propertyMediaRepo.update(mediaId, { is_primary: true }, connection);

    await auditRepo.createAuditLog({
      user_id: userId,
      action: 'SET_PRIMARY_MEDIA',
      entity_type: 'PROPERTY',
      entity_id: existingMedia.property_id,
      old_values: { media_id: null },
      new_values: { media_id: mediaId },
      ip_address: ip,
      user_agent: userAgent
    }, connection);

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

export const reorderMedia = async (propertyId: number, orderData: { id: number, sort_order: number }[], userId: number, ip: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const property = await propertiesRepo.findById(propertyId, connection);
    if (!property) throw new Error('Bien introuvable');

    for (const item of orderData) {
      const media = await propertyMediaRepo.findById(item.id, connection);
      if (media && media.property_id === propertyId) {
        await propertyMediaRepo.update(item.id, { sort_order: item.sort_order }, connection);
      }
    }

    await auditRepo.createAuditLog({
      user_id: userId,
      action: 'REORDER_MEDIA',
      entity_type: 'PROPERTY',
      entity_id: propertyId,
      old_values: null,
      new_values: { reordered: true },
      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, userId: number, ip: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const existingMedia = await propertyMediaRepo.findById(mediaId, connection);
    if (!existingMedia) throw new Error('Média introuvable');

    await propertyMediaRepo.deleteById(mediaId, connection);

    await auditRepo.createAuditLog({
      user_id: userId,
      action: 'DELETE_MEDIA',
      entity_type: 'PROPERTY',
      entity_id: existingMedia.property_id,
      old_values: { media_id: mediaId, url: existingMedia.url },
      new_values: null,
      ip_address: ip,
      user_agent: userAgent
    }, connection);

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