/**
 * Phase 8.8.C (2026-04-29) — Service centralisé pour débit shadow-first
 * sur player/gang/cartel treasury.
 *
 * Pattern : on prend en priorité l'argent shadow (illégal, prioritaire à
 * dépenser), puis on complète sur light (légal). Si shadow+light < amount
 * → opération annulée, retour false.
 *
 * Ce service factorise le pattern existant dans :
 *   - SpecialistService.debitOwner
 *   - GangPayrollService.tryPayFromTreasury (équivalent simplifié)
 *
 * Les services existants restent en place (zéro risque de régression).
 * `PaymentService` est utilisé pour TOUTES les NOUVELLES dépenses Phase
 * 8.9+ (carburant, import stock, indic phone, parking) qui ont la même
 * logique shadow-first.
 *
 * Usage :
 *   const ok = await PaymentService.debitMix({
 *     ownerType: 'player', ownerId: playerId, amount: 5000,
 *   });
 *   if (!ok) throw new Error('Fonds insuffisants');
 */
import { AppDataSource } from '../config/database';
import { PlayerBalances } from '../models/PlayerBalances';
import { Gang } from '../models/Gang';
import { Cartel } from '../models/Cartel';
import { TransactionService } from './transaction.service';
import type { TransactionCategory } from '../models/PlayerTransaction';

const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const gangRepo = () => AppDataSource.getRepository(Gang);
const cartelRepo = () => AppDataSource.getRepository(Cartel);

export type PaymentOwnerType = 'player' | 'gang' | 'cartel';

export interface DebitMixInput {
  ownerType: PaymentOwnerType;
  ownerId: string;
  amount: number;
  /** Categorie pour le log transaction (player only — gang/cartel: pas de log auto). */
  category?: TransactionCategory;
  /** Description pour le log transaction. */
  description?: string;
}

export interface DebitMixResult {
  ok: boolean;
  from_shadow: number;
  from_light: number;
  /** Solde restant après débit (pour info uniquement). */
  remaining_shadow: number;
  remaining_light: number;
}

export class PaymentService {

  /**
   * Débit mixte shadow-first sur player/gang/cartel.
   * Atomique via QueryBuilder UPDATE avec GREATEST(0, ...).
   *
   * Retour `{ok: false, from_shadow:0, from_light:0}` si fonds insuffisants
   * (shadow + light < amount). Aucune mutation DB dans ce cas.
   */
  static async debitMix(input: DebitMixInput): Promise<DebitMixResult> {
    const { ownerType, ownerId, amount } = input;
    if (amount <= 0) {
      return { ok: true, from_shadow: 0, from_light: 0, remaining_shadow: 0, remaining_light: 0 };
    }

    if (ownerType === 'player') {
      const b = await balancesRepo().findOneBy({ player_id: ownerId });
      if (!b) return { ok: false, from_shadow: 0, from_light: 0, remaining_shadow: 0, remaining_light: 0 };
      const shadow = Number(b.infinite_shadow) || 0;
      const light = Number(b.infinite_light) || 0;
      if (shadow + light < amount) {
        return { ok: false, from_shadow: 0, from_light: 0, remaining_shadow: shadow, remaining_light: light };
      }
      const fromShadow = Math.min(shadow, amount);
      const fromLight = amount - fromShadow;
      await balancesRepo().createQueryBuilder().update()
        .set({
          infinite_shadow: () => `GREATEST(0, infinite_shadow - ${fromShadow})`,
          infinite_light: () => `GREATEST(0, infinite_light - ${fromLight})`,
        })
        .where('player_id = :id', { id: ownerId })
        .execute();

      // Log transaction (player only — gang/cartel n'utilisent pas la table player_transactions)
      if (input.category) {
        if (fromShadow > 0) {
          await TransactionService.log({
            player_id: ownerId, category: input.category, type: 'out',
            amount: fromShadow, currency: 'infinite_shadow',
            description: input.description ?? null,
          });
        }
        if (fromLight > 0) {
          await TransactionService.log({
            player_id: ownerId, category: input.category, type: 'out',
            amount: fromLight, currency: 'infinite_light',
            description: input.description ?? null,
          });
        }
      }

      return {
        ok: true,
        from_shadow: fromShadow,
        from_light: fromLight,
        remaining_shadow: shadow - fromShadow,
        remaining_light: light - fromLight,
      };
    }

    if (ownerType === 'gang') {
      const g = await gangRepo().findOneBy({ id: ownerId });
      if (!g) return { ok: false, from_shadow: 0, from_light: 0, remaining_shadow: 0, remaining_light: 0 };
      const ts = Number(g.treasury_shadow) || 0;
      const tl = Number(g.treasury_light) || 0;
      if (ts + tl < amount) {
        return { ok: false, from_shadow: 0, from_light: 0, remaining_shadow: ts, remaining_light: tl };
      }
      const fromShadow = Math.min(ts, amount);
      const fromLight = amount - fromShadow;
      await gangRepo().createQueryBuilder().update()
        .set({
          treasury_shadow: () => `GREATEST(0, treasury_shadow - ${fromShadow})`,
          treasury_light: () => `GREATEST(0, treasury_light - ${fromLight})`,
        })
        .where('id = :id', { id: ownerId })
        .execute();
      return {
        ok: true,
        from_shadow: fromShadow,
        from_light: fromLight,
        remaining_shadow: ts - fromShadow,
        remaining_light: tl - fromLight,
      };
    }

    if (ownerType === 'cartel') {
      const c = await cartelRepo().findOneBy({ id: ownerId });
      if (!c) return { ok: false, from_shadow: 0, from_light: 0, remaining_shadow: 0, remaining_light: 0 };
      const ts = Number(c.treasury_shadow) || 0;
      const tl = Number(c.treasury_light) || 0;
      if (ts + tl < amount) {
        return { ok: false, from_shadow: 0, from_light: 0, remaining_shadow: ts, remaining_light: tl };
      }
      const fromShadow = Math.min(ts, amount);
      const fromLight = amount - fromShadow;
      await cartelRepo().createQueryBuilder().update()
        .set({
          treasury_shadow: () => `GREATEST(0, treasury_shadow - ${fromShadow})`,
          treasury_light: () => `GREATEST(0, treasury_light - ${fromLight})`,
        })
        .where('id = :id', { id: ownerId })
        .execute();
      return {
        ok: true,
        from_shadow: fromShadow,
        from_light: fromLight,
        remaining_shadow: ts - fromShadow,
        remaining_light: tl - fromLight,
      };
    }

    return { ok: false, from_shadow: 0, from_light: 0, remaining_shadow: 0, remaining_light: 0 };
  }

  /**
   * Crédit shadow ou light sur player/gang/cartel.
   * Atomique via QueryBuilder UPDATE.
   */
  static async credit(input: {
    ownerType: PaymentOwnerType;
    ownerId: string;
    amount: number;
    currency: 'shadow' | 'light';
  }): Promise<boolean> {
    const { ownerType, ownerId, amount, currency } = input;
    if (amount <= 0) return true;

    if (ownerType === 'player') {
      const col = currency === 'shadow' ? 'infinite_shadow' : 'infinite_light';
      await balancesRepo().createQueryBuilder().update()
        .set({ [col]: () => `${col} + ${amount}` })
        .where('player_id = :id', { id: ownerId })
        .execute();
      return true;
    }
    if (ownerType === 'gang') {
      const col = currency === 'shadow' ? 'treasury_shadow' : 'treasury_light';
      await gangRepo().createQueryBuilder().update()
        .set({ [col]: () => `${col} + ${amount}` })
        .where('id = :id', { id: ownerId })
        .execute();
      return true;
    }
    if (ownerType === 'cartel') {
      const col = currency === 'shadow' ? 'treasury_shadow' : 'treasury_light';
      await cartelRepo().createQueryBuilder().update()
        .set({ [col]: () => `${col} + ${amount}` })
        .where('id = :id', { id: ownerId })
        .execute();
      return true;
    }
    return false;
  }

  /**
   * Vérifie si l'owner a au moins `amount` (shadow + light). Read-only,
   * pas de mutation. Utilisé pour gating UI (ex: bouton grisé si pas assez
   * pour payer le carburant).
   */
  static async canAfford(ownerType: PaymentOwnerType, ownerId: string, amount: number): Promise<boolean> {
    if (amount <= 0) return true;

    if (ownerType === 'player') {
      const b = await balancesRepo().findOneBy({ player_id: ownerId });
      if (!b) return false;
      return (Number(b.infinite_shadow) || 0) + (Number(b.infinite_light) || 0) >= amount;
    }
    if (ownerType === 'gang') {
      const g = await gangRepo().findOneBy({ id: ownerId });
      if (!g) return false;
      return (Number(g.treasury_shadow) || 0) + (Number(g.treasury_light) || 0) >= amount;
    }
    if (ownerType === 'cartel') {
      const c = await cartelRepo().findOneBy({ id: ownerId });
      if (!c) return false;
      return (Number(c.treasury_shadow) || 0) + (Number(c.treasury_light) || 0) >= amount;
    }
    return false;
  }
}
