import { AppDataSource } from '../config/database';
import { LessThan } from 'typeorm';
import { BankLoan, LoanType, LoanLenderType } from '../models/BankLoan';
import { PlayerBalances } from '../models/PlayerBalances';
import { Player } from '../models/Player';
import { Employment } from '../models/Employment';
import { Business } from '../models/Business';
import { Residence } from '../models/Residence';
import { Warehouse } from '../models/Warehouse';
import { Notification } from '../models/Notification';
import { TransactionService } from './transaction.service';
import { GangServiceUsage } from '../models/GangServiceUsage';
import { GangMission } from '../models/GangMission';

const loanRepo = () => AppDataSource.getRepository(BankLoan);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const playerRepo = () => AppDataSource.getRepository(Player);
const employmentRepo = () => AppDataSource.getRepository(Employment);
const notifRepo = () => AppDataSource.getRepository(Notification);
const serviceUsageRepo = () => AppDataSource.getRepository(GangServiceUsage);
const gangMissionRepo = () => AppDataSource.getRepository(GangMission);

/**
 * Crédits financiers (bank / gang / cartel_peer).
 *
 * Bank :
 *   - Taux aléatoire 3..15%/jour (tiré au lancement, fixe pour la durée).
 *   - Durée : 1j, 7j, 30j.
 *   - Plafond : sum(fiches de paye 6 mois) × 0.5 × (credit_score/500) + valeur bâtiments × 0.3.
 *   - Non-remboursement → hypothèque POIs achetés (revenus redirigés vers la banque).
 *
 * Gang :
 *   - 1000 ∞ × nombre de missions gang complétées.
 *   - Taux similaire bank, durée 7j.
 *
 * Cartel_peer :
 *   - Taux libre fixé par prêteur/emprunteur. Durée libre.
 *   - Non-remboursement → emprunteur devient attaquable par membres du cartel.
 */
export class BankLoanService {

  static randomBankRate(): number {
    return Math.round((0.03 + Math.random() * 0.12) * 1000) / 1000; // 3..15%
  }

  static computePlayerBankCeiling = async (playerId: string): Promise<number> => {
    const sixMonthsAgo = new Date(Date.now() - 180 * 24 * 3600 * 1000);
    const employments = await employmentRepo().find({
      where: { player_id: playerId },
    });
    let payslipSum = 0;
    for (const e of employments) {
      // chaque employment a une salaire mensuel. On considère 6 derniers mois.
      const monthly = (e as any).monthly_salary || (e as any).salary || 0;
      const startMs = new Date((e as any).hired_at || (e as any).created_at || sixMonthsAgo).getTime();
      const workedMonths = Math.min(6, Math.max(0, Math.floor((Date.now() - startMs) / (30 * 24 * 3600 * 1000))));
      payslipSum += monthly * workedMonths;
    }
    const player = await playerRepo().findOneBy({ id: playerId });
    const score = Math.max(1, Math.min(1000, Number(player?.credit_score ?? 500)));
    const payslipPart = payslipSum * 0.5 * (score / 500);

    // Valeur des biens (pour solvabilité)
    const [bizCount, resCount, whCount] = await Promise.all([
      AppDataSource.getRepository(Business).count({ where: { player_id: playerId } }),
      AppDataSource.getRepository(Residence).count({ where: { player_id: playerId } }),
      AppDataSource.getRepository(Warehouse).count({ where: { player_id: playerId } }),
    ]);
    const propertyPart = (bizCount * 50000 + resCount * 30000 + whCount * 20000) * 0.3;

    return Math.floor(payslipPart + propertyPart);
  };

  static async computeGangCreditCeiling(playerId: string, gangId: string): Promise<number> {
    const completed = await gangMissionRepo().count({
      where: { player_id: playerId, gang_id: gangId, status: 'completed' },
    });
    return completed * 1000;
  }

  // ──────────────────────────────────────────────────────────
  // Création
  // ──────────────────────────────────────────────────────────

  static async requestBankLoan(playerId: string, poiId: string, amount: number, durationDays: 1 | 7 | 30): Promise<BankLoan> {
    if (amount <= 0) throw new Error('Montant invalide');
    if (![1, 7, 30].includes(durationDays)) throw new Error('Durée invalide (1, 7 ou 30 jours)');

    const player = await playerRepo().findOneBy({ id: playerId });
    if (!player) throw new Error('Joueur introuvable');
    if (player.active_defaults > 0) throw new Error('Vous avez des crédits en défaut — régularisez d\'abord.');

    const ceiling = await BankLoanService.computePlayerBankCeiling(playerId);
    if (amount > ceiling) throw new Error(`Plafond dépassé : max ${ceiling.toLocaleString('fr-FR')} ∞.`);

    const rate = BankLoanService.randomBankRate();
    const dueAt = new Date(Date.now() + durationDays * 24 * 3600 * 1000);

    const loan = await loanRepo().save(loanRepo().create({
      loan_type: 'bank',
      borrower_player_id: playerId,
      lender_type: 'poi',
      lender_id: poiId,
      principal: amount,
      currency: 'infinite_shadow',
      interest_rate_daily: rate,
      duration_days: durationDays,
      remaining: amount,
      status: 'active',
      due_at: dueAt,
    }));

    // Créditer le joueur en shadow
    await balancesRepo().increment({ player_id: playerId }, 'infinite_shadow', amount);
    await TransactionService.log({
      player_id: playerId,
      category: 'bank',
      type: 'in',
      amount,
      currency: 'infinite_shadow',
      description: `Crédit banque ${(rate * 100).toFixed(2)}%/j / ${durationDays}j`,
    });

    return loan;
  }

  static async requestGangLoan(playerId: string, gangId: string, amount: number): Promise<BankLoan> {
    if (amount <= 0) throw new Error('Montant invalide');
    const ceiling = await BankLoanService.computeGangCreditCeiling(playerId, gangId);
    if (amount > ceiling) throw new Error(`Plafond gang : max ${ceiling.toLocaleString('fr-FR')} ∞ (1000/mission).`);

    const rate = BankLoanService.randomBankRate();
    const dueAt = new Date(Date.now() + 7 * 24 * 3600 * 1000);

    const loan = await loanRepo().save(loanRepo().create({
      loan_type: 'gang',
      borrower_player_id: playerId,
      lender_type: 'gang',
      lender_id: gangId,
      principal: amount,
      currency: 'infinite_shadow',
      interest_rate_daily: rate,
      duration_days: 7,
      remaining: amount,
      status: 'active',
      due_at: dueAt,
    }));

    // Créditer le joueur
    await balancesRepo().increment({ player_id: playerId }, 'infinite_shadow', amount);
    await TransactionService.log({
      player_id: playerId,
      category: 'gang_loan',
      type: 'in',
      amount,
      currency: 'infinite_shadow',
      description: `Crédit gang ${(rate * 100).toFixed(2)}%/j / 7j`,
    });

    // Log usage
    await serviceUsageRepo().save(serviceUsageRepo().create({
      player_id: playerId,
      gang_id: gangId,
      service_type: 'credit',
      amount,
    }));

    return loan;
  }

  static async requestCartelPeerLoan(
    fromPlayerId: string,
    toPlayerId: string,
    cartelId: string,
    amount: number,
    rateDaily: number,
    durationDays: number,
  ): Promise<BankLoan> {
    if (amount <= 0) throw new Error('Montant invalide');
    if (rateDaily < 0 || rateDaily > 1) throw new Error('Taux invalide (0..100%/jour)');
    if (durationDays <= 0 || durationDays > 365) throw new Error('Durée invalide');

    const fromBalance = await balancesRepo().findOneBy({ player_id: fromPlayerId });
    if (!fromBalance) throw new Error('Solde du prêteur introuvable');
    if (Number(fromBalance.infinite_shadow) < amount) throw new Error('Fonds insuffisants');

    const dueAt = new Date(Date.now() + durationDays * 24 * 3600 * 1000);
    const loan = await loanRepo().save(loanRepo().create({
      loan_type: 'cartel_peer',
      borrower_player_id: toPlayerId,
      lender_type: 'player',
      lender_id: fromPlayerId,
      cartel_id: cartelId,
      principal: amount,
      currency: 'infinite_shadow',
      interest_rate_daily: rateDaily,
      duration_days: durationDays,
      remaining: amount,
      status: 'active',
      due_at: dueAt,
    }));

    // Transfert shadow
    await balancesRepo().decrement({ player_id: fromPlayerId }, 'infinite_shadow', amount);
    await balancesRepo().increment({ player_id: toPlayerId }, 'infinite_shadow', amount);
    await TransactionService.log({
      player_id: toPlayerId, category: 'cartel_loan', type: 'in',
      amount, currency: 'infinite_shadow',
      description: `Prêt cartel pair-à-pair ${(rateDaily * 100).toFixed(2)}%/j / ${durationDays}j`,
    });
    await TransactionService.log({
      player_id: fromPlayerId, category: 'cartel_loan', type: 'out',
      amount, currency: 'infinite_shadow',
      description: `Prêt accordé à un membre du cartel`,
    });

    return loan;
  }

  // ──────────────────────────────────────────────────────────
  // Remboursement
  // ──────────────────────────────────────────────────────────

  static async repay(playerId: string, loanId: string, amount: number): Promise<{ remaining: number; repaid_full: boolean; discount_applied?: number }> {
    if (amount <= 0) throw new Error('Montant invalide');
    const loan = await loanRepo().findOneBy({ id: loanId });
    if (!loan || loan.status !== 'active') throw new Error('Prêt introuvable ou inactif');
    if (loan.borrower_player_id !== playerId) throw new Error('Ce prêt n\'est pas le vôtre');

    const balance = await balancesRepo().findOneBy({ player_id: playerId });
    if (!balance) throw new Error('Solde introuvable');
    const paid = Math.min(amount, loan.remaining);
    if (Number(balance.infinite_shadow) < paid) throw new Error('Fonds insuffisants');

    // Remise de 20% sur les intérêts restant si remboursement "Rembourser crédit" (tout d'un coup)
    let discountApplied = 0;
    if (paid >= loan.remaining) {
      // Total repay : appliquer -20% sur la partie intérêts restant (principal supposé connu)
      const interestsRemaining = Math.max(0, loan.remaining - loan.principal);
      discountApplied = Math.floor(interestsRemaining * 0.20);
      const effectivePaid = Math.max(0, paid - discountApplied);
      await balancesRepo().decrement({ player_id: playerId }, 'infinite_shadow', effectivePaid);
      loan.remaining = 0;
      loan.status = 'repaid';
      loan.repaid_at = new Date();
      await loanRepo().save(loan);
      // Verser au prêteur
      if (loan.lender_type === 'player') {
        await balancesRepo().increment({ player_id: loan.lender_id }, 'infinite_shadow', effectivePaid);
      }
      // Réduire active_defaults si c'était une défaillance
      await playerRepo().update({ id: playerId }, { active_defaults: () => 'GREATEST(0, active_defaults - 1)' } as any);
      return { remaining: 0, repaid_full: true, discount_applied: discountApplied };
    }

    await balancesRepo().decrement({ player_id: playerId }, 'infinite_shadow', paid);
    loan.remaining = loan.remaining - paid;
    await loanRepo().save(loan);
    if (loan.lender_type === 'player') {
      await balancesRepo().increment({ player_id: loan.lender_id }, 'infinite_shadow', paid);
    }
    return { remaining: loan.remaining, repaid_full: false };
  }

  // ──────────────────────────────────────────────────────────
  // CRON : accrual quotidien + default
  // ──────────────────────────────────────────────────────────

  static async accrueInterestAll(): Promise<{ accrued: number; total_interest: number; defaulted: number }> {
    const active = await loanRepo().find({ where: { status: 'active' } });
    const now = new Date();
    let accrued = 0, totalInterest = 0, defaulted = 0;

    for (const loan of active) {
      const last = loan.last_accrual_at ? new Date(loan.last_accrual_at) : new Date(loan.created_at);
      const daysElapsed = Math.floor((now.getTime() - last.getTime()) / (24 * 3600 * 1000));
      if (daysElapsed <= 0) continue;

      // Intérêt composé jour par jour
      let rem = loan.remaining;
      const rate = Number(loan.interest_rate_daily);
      for (let i = 0; i < daysElapsed; i++) {
        const interest = Math.ceil(rem * rate);
        rem += interest;
        totalInterest += interest;
      }
      loan.remaining = rem;
      loan.last_accrual_at = now;

      // Default check
      if (now >= new Date(loan.due_at)) {
        loan.status = 'defaulted';
        loan.default_at = now;
        await playerRepo().update({ id: loan.borrower_player_id }, { active_defaults: () => 'active_defaults + 1' } as any);
        defaulted++;
        await notifRepo().save(notifRepo().create({
          player_id: loan.borrower_player_id,
          type: 'loan_defaulted',
          title: 'Crédit en défaut',
          message: `Votre crédit ${loan.loan_type} est en défaut de paiement. ${loan.remaining.toLocaleString('fr-FR')} ∞ à rembourser.`,
        }));
      }
      await loanRepo().save(loan);
      accrued++;
    }
    return { accrued, total_interest: totalInterest, defaulted };
  }

  // ──────────────────────────────────────────────────────────
  // Queries
  // ──────────────────────────────────────────────────────────

  static async listByBorrower(playerId: string) {
    return loanRepo().find({
      where: { borrower_player_id: playerId },
      order: { created_at: 'DESC' },
    });
  }

  static async listByLender(lenderType: LoanLenderType, lenderId: string) {
    return loanRepo().find({
      where: { lender_type: lenderType, lender_id: lenderId },
      order: { created_at: 'DESC' },
    });
  }

  static async listByCartel(cartelId: string) {
    return loanRepo().find({ where: { cartel_id: cartelId }, order: { created_at: 'DESC' } });
  }

  /** Vérifie si un joueur est attaquable par les membres de son cartel (dette non remboursée en défaut). */
  static async isAttackableByCartelPeers(playerId: string): Promise<{ attackable: boolean; defaulted_loans: number }> {
    const count = await loanRepo().count({
      where: { borrower_player_id: playerId, loan_type: 'cartel_peer', status: 'defaulted' },
    });
    return { attackable: count > 0, defaulted_loans: count };
  }
}
