import * as paymentSchedulesRepo from '../repositories/paymentSchedules.repository';
import * as acquirersRepo from '../repositories/acquirers.repository';
import { createAuditLog } from '../repositories/audit.repository';
import { pool } from '../config/database';

export const getScheduleByAcquirerId = async (acquirerId: number) => {
  const acquirer = await acquirersRepo.findById(acquirerId);
  if (!acquirer) throw new Error('Acquéreur introuvable');
  
  const schedule = await paymentSchedulesRepo.findScheduleByUnitId(acquirer.unit_id);
  if (!schedule) return null;

  const items = await paymentSchedulesRepo.findItemsByScheduleId(schedule.id);
  return { ...schedule, items };
};

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

    const acquirer = await acquirersRepo.findById(acquirerId, connection);
    if (!acquirer) throw new Error('Acquéreur introuvable');

    if (acquirer.unit_id !== data.unit_id) {
      throw new Error('Le lot spécifié ne correspond pas à cet acquéreur');
    }

    const existing = await paymentSchedulesRepo.findScheduleByUnitId(data.unit_id);
    if (existing) {
      throw new Error('Un échéancier actif existe déjà pour ce lot');
    }

    // Calcul vérifier le total
    const totalItems = data.items.reduce((sum: number, item: any) => sum + item.amount, 0);
    if (Math.abs(totalItems - data.total_amount) > 0.01) {
      throw new Error('La somme des échéances ne correspond pas au montant total');
    }

    const scheduleId = await paymentSchedulesRepo.createSchedule({
      acquirer_id: acquirerId,
      unit_id: data.unit_id,
      total_amount: data.total_amount
    }, connection);

    for (const item of data.items) {
      await paymentSchedulesRepo.createItem({
        payment_schedule_id: scheduleId,
        label: item.label,
        due_date: item.due_date,
        amount: item.amount,
        notes: item.notes
      }, connection);
    }

    await createAuditLog({
      user_id: adminId,
      action: 'SCHEDULE_CREATED',
      entity_type: 'PAYMENT_SCHEDULE',
      entity_id: scheduleId,
      ip_address: ip,
      user_agent: userAgent
    }, connection);

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

export const updateScheduleItem = async (itemId: number, data: any, adminId: number, ip?: string, userAgent?: string) => {
  const item = await paymentSchedulesRepo.findItemById(itemId);
  if (!item) throw new Error('Échéance introuvable');

  await paymentSchedulesRepo.updateItem(itemId, data);

  await createAuditLog({
    user_id: adminId,
    action: 'SCHEDULE_UPDATED', // Simplification de l'action pour l'item
    entity_type: 'PAYMENT_SCHEDULE_ITEM',
    entity_id: itemId,
    ip_address: ip,
    user_agent: userAgent
  });
};
