import * as paymentsRepo from '../repositories/payments.repository';
import * as paymentSchedulesRepo from '../repositories/paymentSchedules.repository';
import { createAuditLog } from '../repositories/audit.repository';
import { pool } from '../config/database';

export const getAllPayments = async (reqUserId: number, userRole: string) => {
  if (!['SUPER_ADMIN', 'ADMIN'].includes(userRole)) {
    throw new Error('Accès non autorisé à l\'ensemble des paiements');
  }
  return paymentsRepo.findAllWithAcquirers();
};

export const getPaymentsByItem = async (itemId: number) => {
  return paymentsRepo.findByItemId(itemId);
};

export const getPaymentById = async (id: number) => {
  return paymentsRepo.findById(id);
};

const updateItemStatusAfterPayment = async (itemId: number, connection: any) => {
  const item = await paymentSchedulesRepo.findItemById(itemId, connection);
  if (!item) return;

  const totalPaid = await paymentsRepo.getTotalPaidForItem(itemId, connection);
  
  let newStatus = 'PENDING';
  let paidAt = null;

  if (totalPaid > 0) {
    if (totalPaid >= item.amount) {
      newStatus = 'PAID';
      paidAt = new Date(); // Normalement on prendrait la date du dernier paiement validé
    } else {
      newStatus = 'PARTIAL';
    }
  } else {
    // Si la date d'échéance est passée et rien n'est payé
    if (new Date(item.due_date) < new Date()) {
      newStatus = 'OVERDUE';
    }
  }

  if (item.status !== newStatus) {
    await paymentSchedulesRepo.updateItem(itemId, { status: newStatus, paid_at: paidAt }, connection);
  }
};

export const createPayment = async (itemId: number, data: any, adminId: number, ip?: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const item = await paymentSchedulesRepo.findItemById(itemId, connection);
    if (!item) throw new Error('Échéance introuvable');

    const totalPaid = await paymentsRepo.getTotalPaidForItem(itemId, connection);
    const amountToPay = Number(data.amount);
    const remaining = Number(item.amount) - totalPaid;
    
    if (remaining <= 0) {
      throw new Error(`Cette échéance est déjà intégralement soldée (reste à payer : 0 FCFA). Impossible d'ajouter un nouveau paiement.`);
    }

    if (amountToPay <= 0) {
      throw new Error(`Le montant du paiement doit être supérieur à 0 FCFA.`);
    }

    // We allow a small tolerance (e.g. 0.01) for floating point inaccuracies if needed, but here simple comparison is okay.
    if (amountToPay > remaining + 0.01) {
      throw new Error(`Le montant du paiement (${amountToPay.toLocaleString('fr-FR')} FCFA) dépasse le reste à payer (${remaining.toLocaleString('fr-FR')} FCFA).`);
    }

    data.recorded_by = adminId;
    const paymentId = await paymentsRepo.create(itemId, data, connection);

    // Recalculer le statut de l'échéance
    await updateItemStatusAfterPayment(itemId, connection);

    await createAuditLog({
      user_id: adminId,
      action: 'PAYMENT_CREATED',
      entity_type: 'PAYMENT',
      entity_id: paymentId,
      ip_address: ip,
      user_agent: userAgent
    }, connection);

    await connection.commit();

    // Envoyer l'accusé / reçu de paiement par email à l'acquéreur (et copie à l'agence) en arrière-plan
    // pour ne pas bloquer la réponse HTTP du paiement
    setImmediate(async () => {
      try {
        const details = await paymentsRepo.findPaymentDetailsForReceipt(itemId);
        if (details) {
          const { sendPaymentReceiptEmail } = await import('./notificationSender.service');
          await sendPaymentReceiptEmail({
            acquirerEmail: details.acquirer_email,
            acquirerName: details.acquirer_name,
            amount: data.amount,
            paymentDate: data.payment_date,
            paymentMethod: data.payment_method,
            reference: data.reference,
            itemLabel: details.item_label,
            unitNumber: details.unit_number,
            projectName: details.project_name,
            remainingAmount: Number(details.total_remaining) || 0
          });
        }
      } catch (emailErr) {
        console.error('Erreur lors de l\'envoi du reçu de paiement:', emailErr);
      }
    });

    return { id: paymentId };
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};

export const updatePayment = async (id: number, data: any, adminId: number, ip?: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const payment = await paymentsRepo.findById(id, connection);
    if (!payment) throw new Error('Paiement introuvable');

    const item = await paymentSchedulesRepo.findItemById(payment.payment_schedule_item_id, connection);
    if (!item) throw new Error('Échéance introuvable');

    if (data.amount !== undefined) {
      const totalPaid = await paymentsRepo.getTotalPaidForItem(item.id, connection);
      const newAmount = Number(data.amount);
      const oldAmount = Number(payment.amount);
      const remaining = Number(item.amount) - (totalPaid - oldAmount);

      if (newAmount > remaining + 0.01) {
        throw new Error(`Le nouveau montant (${newAmount.toLocaleString()}) dépasse le reste à payer possible pour cette échéance (${remaining.toLocaleString()}).`);
      }
    }

    await paymentsRepo.update(id, data, connection);

    // Recalculer le statut
    await updateItemStatusAfterPayment(payment.payment_schedule_item_id, connection);

    await createAuditLog({
      user_id: adminId,
      action: 'PAYMENT_UPDATED',
      entity_type: 'PAYMENT',
      entity_id: id,
      ip_address: ip,
      user_agent: userAgent
    }, connection);

    await connection.commit();
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};

export const deletePayment = async (id: number, adminId: number, ip?: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const payment = await paymentsRepo.findById(id, connection);
    if (!payment) throw new Error('Paiement introuvable');

    await paymentsRepo.remove(id, connection);

    // Recalculer le statut
    await updateItemStatusAfterPayment(payment.payment_schedule_item_id, connection);

    await createAuditLog({
      user_id: adminId,
      action: 'PAYMENT_DELETED',
      entity_type: 'PAYMENT',
      entity_id: id,
      ip_address: ip,
      user_agent: userAgent
    }, connection);

    await connection.commit();
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};
