/**
 * Phase 7 (2026-04-29) — Amendes au jugement.
 *
 * Une amende = un BankLoan avec loan_type='court_fine' :
 *   - principal = montant total
 *   - currency = infinite_light
 *   - interest_rate_daily = 0 (pas d'intérêt sur amende)
 *   - duration_days = 30
 *   - daily_amount = principal / 30 (calculé via metadata)
 *
 * Cron quotidien `processDailyDecay` : pour chaque amende active,
 * débite `daily_amount` du joueur. Si fonds insuffisants → 1 jour
 * de prison via PrisonAssignmentService + status='defaulted'.
 *
 * Référence : BankLoanService gère déjà `loan_type IN ('bank','gang','cartel_peer')`.
 * On ajoute `'court_fine'` qui suit son propre flow (séparé de accrueInterestAll).
 */
import { AppDataSource } from '../config/database';
import { BankLoan } from '../models/BankLoan';
import { PlayerBalances } from '../models/PlayerBalances';
import { Notification } from '../models/Notification';
import { TransactionService } from './transaction.service';
import { CriminalRecord } from '../models/CriminalRecord';

const loanRepo = () => AppDataSource.getRepository(BankLoan);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const notifRepo = () => AppDataSource.getRepository(Notification);
const recordRepo = () => AppDataSource.getRepository(CriminalRecord);

const FINE_DURATION_DAYS = 30;

export class CourtFineService {
  /**
   * Crée une amende (BankLoan court_fine) pour un joueur lié à un criminal_record.
   * Le montant total est divisé en 30 paiements quotidiens (principal/30).
   */
  static async createFine(
    playerId: string,
    recordId: string,
    amount: number,
  ): Promise<BankLoan> {
    if (amount <= 0) throw new Error('Montant amende invalide');

    const dailyAmount = Math.ceil(amount / FINE_DURATION_DAYS);
    const dueAt = new Date(Date.now() + FINE_DURATION_DAYS * 86400 * 1000);

    const loan = await loanRepo().save(loanRepo().create({
      // Note : loan_type est varchar côté DB, accepte 'court_fine' sans migration.
      // Le type TS LoanType ne le contient pas — cast assumé.
      loan_type: 'court_fine' as any,
      borrower_player_id: playerId,
      lender_type: 'poi' as any, // pas de POI tribunal direct, mais lender_type doit être valide
      lender_id: '00000000-0000-0000-0000-000000000000', // sentinel pour court (pas de POI lié)
      principal: amount,
      currency: 'infinite_light',
      interest_rate_daily: 0,
      duration_days: FINE_DURATION_DAYS,
      remaining: amount,
      status: 'active',
      due_at: dueAt,
      metadata: {
        criminal_record_id: recordId,
        daily_amount: dailyAmount,
        fine_kind: 'judgment',
      },
    }));

    return loan;
  }

  /**
   * CRON daily — pour chaque amende active, débit le daily_amount.
   * Si fonds insuffisants, mark defaulted + 1 jour prison.
   * Si remaining ≤ 0 ou now > due_at, mark repaid.
   */
  static async processDailyDecay(): Promise<{
    paid: number;
    defaulted: number;
    completed: number;
  }> {
    const fines = await loanRepo().find({
      where: { loan_type: 'court_fine' as any, status: 'active' },
    });

    let paid = 0;
    let defaulted = 0;
    let completed = 0;

    for (const fine of fines) {
      const meta = (fine.metadata as any) || {};
      const dailyAmount = Number(meta.daily_amount ?? Math.ceil(fine.principal / FINE_DURATION_DAYS));

      // Cas 1 : amende soldée
      if (fine.remaining <= 0) {
        await loanRepo().update({ id: fine.id }, {
          status: 'repaid',
          repaid_at: new Date(),
        });
        completed++;
        continue;
      }

      // Cas 2 : échéance dépassée → close + remaining considéré soldé (le decay quotidien arrive avant)
      if (new Date() > new Date(fine.due_at)) {
        // Si encore remaining > 0 et due_at dépassé : default
        await loanRepo().update({ id: fine.id }, {
          status: 'defaulted',
          default_at: new Date(),
        });
        defaulted++;
        continue;
      }

      // Cas 3 : débit quotidien
      const balance = await balancesRepo().findOneBy({ player_id: fine.borrower_player_id });
      const haveLight = Number(balance?.infinite_light ?? 0);
      const debit = Math.min(dailyAmount, fine.remaining);

      if (haveLight < debit) {
        // Fonds insuffisants → 1 jour prison + default
        await loanRepo().update({ id: fine.id }, {
          status: 'defaulted',
          default_at: new Date(),
        });
        try {
          const { PrisonAssignmentService } = await import('./prison-assignment.service');
          await PrisonAssignmentService.assignPrison(fine.borrower_player_id, 1);
        } catch (err) {
          console.error('[CourtFine] assignPrison error:', (err as Error).message);
        }
        try {
          await notifRepo().save(notifRepo().create({
            player_id: fine.borrower_player_id,
            type: 'system',
            title: 'Amende impayée — 1 jour prison',
            message: `Vous n'avez pas pu payer ${debit.toLocaleString('fr-FR')} ∞ light aujourd'hui. 1 jour de prison.`,
          }));
        } catch { /* silent */ }
        // Marquer le record judicial_step='imprisoned' s'il était fine_active
        if (meta.criminal_record_id) {
          try {
            await recordRepo().update(
              { id: meta.criminal_record_id },
              { judicial_step: 'imprisoned' as any, outcome: 'imprisoned' as any },
            );
          } catch { /* silent */ }
        }
        defaulted++;
        continue;
      }

      // Débit OK
      await balancesRepo().decrement({ player_id: fine.borrower_player_id }, 'infinite_light', debit);
      const newRemaining = fine.remaining - debit;
      const updates: any = { remaining: newRemaining, last_accrual_at: new Date() };
      if (newRemaining <= 0) {
        updates.status = 'repaid';
        updates.repaid_at = new Date();
        completed++;
        // Marquer le record released si entièrement soldé
        if (meta.criminal_record_id) {
          try {
            await recordRepo().update(
              { id: meta.criminal_record_id },
              { judicial_step: 'released' as any, outcome: 'fine_only' as any },
            );
          } catch { /* silent */ }
        }
      }
      await loanRepo().update({ id: fine.id }, updates);
      try {
        await TransactionService.log({
          player_id: fine.borrower_player_id,
          category: 'crime',
          type: 'out',
          amount: debit,
          currency: 'infinite_light',
          description: `Amende judiciaire (${dailyAmount}/${FINE_DURATION_DAYS}j)`,
        });
      } catch { /* silent */ }
      paid++;
    }

    return { paid, defaulted, completed };
  }

  /**
   * Liste les amendes actives d'un joueur (banner UI + Phone).
   */
  static async listActiveFines(playerId: string): Promise<BankLoan[]> {
    return loanRepo().find({
      where: {
        loan_type: 'court_fine' as any,
        borrower_player_id: playerId,
        status: 'active',
      },
      order: { created_at: 'DESC' },
    });
  }
}
