import { AppDataSource } from '../config/database';
import { Specialist, SpecialistRole } from '../models/Specialist';
import { SpecialistAttachment, SpecialistOwnerType } from '../models/SpecialistAttachment';
import { PlayerBalances } from '../models/PlayerBalances';
import { Cartel } from '../models/Cartel';
import { Gang } from '../models/Gang';
import { Notification } from '../models/Notification';
import { PaymentService } from './payment.service';

const specRepo = () => AppDataSource.getRepository(Specialist);
const attRepo = () => AppDataSource.getRepository(SpecialistAttachment);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const cartelRepo = () => AppDataSource.getRepository(Cartel);
const gangRepo = () => AppDataSource.getRepository(Gang);
const notifRepo = () => AppDataSource.getRepository(Notification);

/**
 * Spécialistes (avocats, comptables, indics, détectives, médecins perso).
 *
 * Formule salaire (lawyer / accountant / informant) :
 *   monthly = 2000 + (skill_level − 1) × 1444  → skill 1 = 2000, skill 10 = 15000
 *   daily   = round(monthly / 30 / 10) × 10
 *
 * Phase 17 (2026-05-04) — Détective + Médecin perso :
 *   Coût flat 100 ∞ / jour quel que soit le skill (skill = cosmétique pour
 *   l'affichage 1-10 étoiles, sans impact sur le prix). monthly = 100 × 30.
 *
 * Discount multi-rattachement : 20% par rattachement additionnel du même
 * specialist. N attachments → chaque attachment paie daily × (1 - 0.20 × (N-1)),
 * floor 10%. Détective et médecin sont à 1 max par owner donc pas de discount
 * applicable.
 *
 * Limites max par owner par rôle :
 *   lawyer / accountant / informant : 3 max
 *   detective / medic               : 1 max (consigne user)
 *
 * Modificateurs (lawyer / accountant / informant) :
 *   Lawyer    : -4% sentence × (skill/10) par avocat, max 3.
 *   Informant : -3% heat_gain × (skill/10) par indic, max 3.
 *   Accountant: -5% transaction_trace × (skill/10) par comptable, max 3.
 *
 * Détective : 1 rapport / 7 jours (après embauche ≥ 7 jours), révèle 1 POI
 *   player-stocked dans poi_revelations (TTL 7 jours).
 * Médecin perso : +1 PV / heure passif (cron), + on-call 100 ∞ / PV manquant
 *   à 1 PV / minute (livraison post-paiement).
 */
const MAX_PER_OWNER_ROLE_MAP: Record<SpecialistRole, number> = {
  lawyer: 3,
  accountant: 3,
  informant: 3,
  detective: 1,
  medic: 1,
};

/**
 * Phase 17 (2026-05-04) — Fourchettes de tarif/jour selon le rôle.
 * Le joueur choisit son tarif dans la fourchette à l'embauche, stocké
 * dans SpecialistAttachment.chosen_daily_rate.
 *
 * • lawyer/accountant/informant : prix fixe selon skill (computeDaily)
 * • detective : [10 × skill, 20 × skill] — paye haute = bonus chance gros lot
 * • medic     : [80, 140] flat — soin identique quel que soit le tarif
 */

export class SpecialistService {
  /** @deprecated 2026-05-04 — utiliser getMaxPerOwnerRole(role) à la place. */
  static readonly MAX_PER_OWNER_ROLE = 3;
  static readonly MULTI_ATTACHMENT_DISCOUNT = 20; // %

  /** Phase 17 — limite max par owner selon le rôle (1 detective/medic, 3 sinon). */
  static getMaxPerOwnerRole(role: SpecialistRole): number {
    return MAX_PER_OWNER_ROLE_MAP[role] ?? 3;
  }

  static computeMonthly(skill: number, role?: SpecialistRole): number {
    // Detective + medic : monthly cosmétique (le vrai prix est négocié
    // par owner dans chosen_daily_rate, fourchette getDailyRateRange).
    // On stocke `salary_monthly` = milieu de fourchette × 30 pour garder
    // un affichage indicatif dans la liste NPC.
    if (role === 'detective') {
      const s = Math.max(1, Math.min(10, Math.trunc(skill)));
      const mid = 15 * s; // milieu de [10s, 20s]
      return mid * 30;
    }
    if (role === 'medic') {
      return 110 * 30; // milieu de [80, 140]
    }
    const s = Math.max(1, Math.min(10, Math.trunc(skill)));
    return 2000 + (s - 1) * 1444;
  }

  static computeDaily(skill: number, role?: SpecialistRole): number {
    if (role === 'detective') {
      const s = Math.max(1, Math.min(10, Math.trunc(skill)));
      return 15 * s; // affichage indicatif = milieu fourchette
    }
    if (role === 'medic') {
      return 110; // affichage indicatif = milieu de [80, 140]
    }
    const monthly = SpecialistService.computeMonthly(skill);
    return Math.round(monthly / 30 / 10) * 10;
  }

  /**
   * Phase 17 (2026-05-04) — Fourchette de tarif/jour [min, max] que
   * l'owner peut choisir lors de l'embauche, selon le rôle.
   */
  static getDailyRateRange(role: SpecialistRole, skillLevel: number): [number, number] {
    if (role === 'detective') {
      const s = Math.max(1, Math.min(10, Math.trunc(skillLevel)));
      return [10 * s, 20 * s];
    }
    if (role === 'medic') {
      return [80, 140];
    }
    // lawyer / accountant / informant : prix fixe selon skill
    const fixed = SpecialistService.computeDaily(skillLevel);
    return [fixed, fixed];
  }

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

  static async createNpc(data: {
    role: SpecialistRole;
    name: string;
    skill_level: number;
    bio?: string;
  }): Promise<Specialist> {
    const monthly = SpecialistService.computeMonthly(data.skill_level, data.role);
    const daily = SpecialistService.computeDaily(data.skill_level, data.role);
    return specRepo().save(specRepo().create({
      role: data.role,
      name: data.name,
      skill_level: data.skill_level,
      salary_monthly: monthly,
      salary_daily: daily,
      bio: data.bio || null,
      is_npc: true,
    }));
  }

  // ──────────────────────────────────────────────────────────
  // Rattachement / résiliation
  // ──────────────────────────────────────────────────────────

  static async hire(
    ownerType: SpecialistOwnerType,
    ownerId: string,
    specialistId: string,
    chosenDailyRate?: number,
  ): Promise<SpecialistAttachment> {
    const spec = await specRepo().findOneBy({ id: specialistId });
    if (!spec) throw new Error('Spécialiste introuvable');

    // Phase 17 (2026-05-04) — Médecin perso uniquement attachable à un
    // player (pas gang/cartel — concept "médecin personnel" n'a pas de
    // sens à l'échelle d'un collectif).
    if (spec.role === 'medic' && ownerType !== 'player') {
      throw new Error('Le médecin perso ne peut être attaché qu\'à un joueur, pas à un gang ou un cartel.');
    }

    // Vérifier limite par (owner, role) — 3 standard, 1 pour detective/medic
    const countActive = await attRepo()
      .createQueryBuilder('a')
      .innerJoin(Specialist, 's', 's.id = a.specialist_id')
      .where('a.owner_type = :t AND a.owner_id = :id AND a.is_active = true AND s.role = :r', {
        t: ownerType, id: ownerId, r: spec.role,
      })
      .getCount();
    const maxAllowed = SpecialistService.getMaxPerOwnerRole(spec.role);
    if (countActive >= maxAllowed) {
      throw new Error(`Maximum ${maxAllowed} ${spec.role} par ${ownerType}`);
    }

    // Vérifier pas déjà rattaché à cet owner
    const existing = await attRepo().findOne({
      where: { specialist_id: specialistId, owner_type: ownerType, owner_id: ownerId, is_active: true },
    });
    if (existing) throw new Error('Ce spécialiste est déjà rattaché à cette entité');

    // Phase 17 (2026-05-04) — Tarif/jour négocié dans la fourchette
    // autorisée par le rôle. Si non précisé, on prend le tarif median
    // (computeDaily) pour rétrocompat avec les anciens callers.
    const [minRate, maxRate] = SpecialistService.getDailyRateRange(spec.role, spec.skill_level);
    const rateToUse = chosenDailyRate ?? SpecialistService.computeDaily(spec.skill_level, spec.role);
    if (rateToUse < minRate || rateToUse > maxRate) {
      throw new Error(`Tarif ${rateToUse} hors fourchette [${minRate}, ${maxRate}] pour ${spec.role} skill ${spec.skill_level}`);
    }

    // Discount multi-attachment : 20% par attachment existant du même specialist
    const totalActive = await attRepo().count({
      where: { specialist_id: specialistId, is_active: true },
    });
    const discount = Math.min(60, totalActive * SpecialistService.MULTI_ATTACHMENT_DISCOUNT);

    const next = new Date();
    next.setUTCHours(next.getUTCHours() + 24);

    // Phase 17 — Initialiser next_report_at si detective (1ᵉʳ rapport
    // dans 7 jours).
    const nextReport = spec.role === 'detective'
      ? new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
      : null;

    const att = attRepo().create({
      specialist_id: specialistId,
      owner_type: ownerType,
      owner_id: ownerId,
      discount_pct: discount,
      is_active: true,
      next_payment_due: next,
      chosen_daily_rate: rateToUse,
      next_report_at: nextReport,
    });
    const saved = await attRepo().save(att);

    // Phase 17.2 (2026-05-05) — Notif d'embauche pour détective (consigne
    // user verbatim : "A l'embauche première notif : 'On va faire de notre
    // mieux pour vous débusquer les infos utiles à votre activité…'").
    // Pour les autres rôles : notif silencieuse côté UX (pas demandée).
    if (spec.role === 'detective') {
      try {
        const recipients = await SpecialistService.resolveNotifRecipients(
          ownerType, ownerId,
        );
        for (const pid of recipients) {
          await notifRepo().save(notifRepo().create({
            player_id: pid,
            type: 'system',
            title: `Enquêteur ${spec.name} embauché`,
            message: 'On va faire de notre mieux pour vous débusquer les infos utiles à votre activité…',
          }));
        }
      } catch { /* silent : la notif n'est pas critique pour l'embauche */ }
    }

    return saved;
  }

  /**
   * Phase 17.2 (2026-05-05) — Résout les player_id à notifier selon scope :
   *   • player → [ownerId]
   *   • gang   → leader + bras_droit (humains)
   *   • cartel → tous CartelMember.is_admin (primary_player_id)
   * Mirror de DetectiveService.resolveNotifRecipients (factorisé ici pour
   * que les notifications spé en général puissent réutiliser).
   */
  private static async resolveNotifRecipients(
    ownerType: SpecialistOwnerType,
    ownerId: string,
  ): Promise<string[]> {
    if (ownerType === 'player') return [ownerId];
    if (ownerType === 'gang') {
      const { GangMember } = await import('../models/GangMember');
      const repo = AppDataSource.getRepository(GangMember);
      const leadership = await repo.find({
        where: [
          { gang_id: ownerId, role: 'leader' as any },
          { gang_id: ownerId, role: 'bras_droit' as any },
        ],
        select: { player_id: true },
      });
      const { Player } = await import('../models/Player');
      const playerRepo = AppDataSource.getRepository(Player);
      const ids = leadership.map((l) => l.player_id);
      if (ids.length === 0) return [];
      const humans = await playerRepo.find({
        where: ids.map((id) => ({ id, is_npc: false as any })),
        select: { id: true },
      });
      return humans.map((p) => p.id);
    }
    if (ownerType === 'cartel') {
      const { CartelMember } = await import('../models/CartelMember');
      const cmRepo = AppDataSource.getRepository(CartelMember);
      const admins = await cmRepo.find({
        where: { cartel_id: ownerId, is_admin: true as any, status: 'active' as any },
        select: { primary_player_id: true } as any,
      });
      return admins
        .map((a: any) => a.primary_player_id)
        .filter((id: string | null) => !!id) as string[];
    }
    return [];
  }

  static async fire(attachmentId: string): Promise<void> {
    const a = await attRepo().findOneBy({ id: attachmentId });
    if (!a) throw new Error('Rattachement introuvable');
    a.is_active = false;
    a.fired_at = new Date();
    a.inactive_reason = 'fired';
    await attRepo().save(a);
  }

  /**
   * Phase 17 (2026-05-04) — Cron daily payment.
   *
   * Pour chaque attachment actif avec next_payment_due <= NOW :
   *   • Coût quotidien = chosen_daily_rate × (1 - discount_pct/100)
   *   • Tente débit shadow-first via PaymentService.debitMix
   *   • Si OK : update last_paid_at + next_payment_due += 24h
   *   • Si KO (fonds insuffisants) : is_active=false, inactive_reason=
   *     'unpaid', notif owner. Le détective ne fournira plus de rapport
   *     hebdo, le médecin ne soigne plus en passive, l'avocat/comptable/
   *     indic ne donne plus son coef.
   *
   * Idempotent : un attachment déjà payé aujourd'hui (next_payment_due
   * dans le futur) est skippé.
   */
  static async processDailyPayments(): Promise<{
    paid: number;
    insolvent: number;
    total_debited: number;
  }> {
    const due = await attRepo()
      .createQueryBuilder('a')
      .innerJoinAndSelect('a.specialist', 's')
      .where('a.is_active = true')
      .andWhere('a.next_payment_due IS NOT NULL')
      .andWhere('a.next_payment_due <= NOW()')
      .getMany();

    let paid = 0;
    let insolvent = 0;
    let totalDebited = 0;

    for (const att of due) {
      try {
        const baseRate = att.chosen_daily_rate ?? att.specialist.salary_daily;
        const discount = Number(att.discount_pct) || 0;
        const cost = Math.max(0, Math.round(baseRate * (1 - discount / 100)));

        if (cost === 0) {
          // Discount 100% (improbable) : on skippe le débit mais avance
          // quand même next_payment_due pour éviter loop.
          att.last_paid_at = new Date();
          att.next_payment_due = new Date(Date.now() + 24 * 60 * 60 * 1000);
          await attRepo().save(att);
          paid++;
          continue;
        }

        const result = await PaymentService.debitMix({
          ownerType: att.owner_type as 'player' | 'gang' | 'cartel',
          ownerId: att.owner_id,
          amount: cost,
          category: 'health' as any, // catégorie générique pour ressources spé
          description: `Salaire ${att.specialist.role} ${att.specialist.name} (${cost} ∞/jour)`,
        });

        if (!result.ok) {
          // Fonds insuffisants : désactive l'attachment
          att.is_active = false;
          att.inactive_reason = 'unpaid';
          att.fired_at = new Date();
          await attRepo().save(att);
          insolvent++;

          // Notif owner (player only — gang/cartel : log console pour Phase 4)
          if (att.owner_type === 'player') {
            try {
              await notifRepo().save(notifRepo().create({
                player_id: att.owner_id,
                type: 'system',
                title: `${att.specialist.name} licencié`,
                message:
                  `Fonds insuffisants pour le salaire quotidien (${cost} ∞ requis). ` +
                  `${att.specialist.name} a quitté ton service. ` +
                  `Tu peux le re-recruter quand tes finances le permettront.`,
              }));
            } catch { /* silent */ }
          } else {
            console.log(`[Specialist] ${att.owner_type} ${att.owner_id} : ${att.specialist.name} licencié (insolvent ${cost} ∞)`);
          }
          continue;
        }

        // Paiement OK
        att.last_paid_at = new Date();
        att.next_payment_due = new Date(Date.now() + 24 * 60 * 60 * 1000);
        await attRepo().save(att);
        paid++;
        totalDebited += cost;
      } catch (err) {
        console.error('[Specialist] processDailyPayment failed for', att.id, ':', (err as Error).message);
      }
    }

    return { paid, insolvent, total_debited: totalDebited };
  }

  static async listForOwner(ownerType: SpecialistOwnerType, ownerId: string) {
    const attachments = await attRepo().find({
      where: { owner_type: ownerType, owner_id: ownerId, is_active: true },
      relations: ['specialist'],
    });
    return attachments.map(a => ({
      attachment_id: a.id,
      specialist_id: a.specialist_id,
      name: a.specialist.name,
      role: a.specialist.role,
      skill_level: a.specialist.skill_level,
      salary_daily: a.specialist.salary_daily,
      discount_pct: Number(a.discount_pct),
      effective_daily: Math.round(a.specialist.salary_daily * (1 - Number(a.discount_pct) / 100) / 10) * 10,
      hired_at: a.hired_at,
      last_paid_at: a.last_paid_at,
      next_payment_due: a.next_payment_due,
    }));
  }

  static async listNpcPool(role: SpecialistRole, minSkill = 1, maxSkill = 10) {
    return specRepo().createQueryBuilder('s')
      .where('s.role = :r AND s.is_npc = true', { r: role })
      .andWhere('s.skill_level BETWEEN :min AND :max', { min: minSkill, max: maxSkill })
      .orderBy('s.skill_level', 'DESC')
      .getMany();
  }

  // ──────────────────────────────────────────────────────────
  // Modificateurs appliqués par les services consommateurs
  // ──────────────────────────────────────────────────────────

  /**
   * Calcule le facteur de réduction selon les spécialistes actifs rattachés.
   * Returns 0..1 (1 = full price/penalty, 0 = totally mitigated).
   */
  static async getModifier(
    ownerType: SpecialistOwnerType,
    ownerId: string,
    role: SpecialistRole,
  ): Promise<number> {
    // Detective/medic n'agissent pas via un coefficient (ils ont leurs
    // propres mécanismes : reveal POI / heal). Court-circuit ici.
    if (role === 'detective' || role === 'medic') return 1;

    const attachments = await attRepo().find({
      where: { owner_type: ownerType, owner_id: ownerId, is_active: true },
      relations: ['specialist'],
    });
    const maxForRole = SpecialistService.getMaxPerOwnerRole(role);
    const filtered = attachments.filter(a => a.specialist.role === role).slice(0, maxForRole);

    let coef = 1;
    for (const a of filtered) {
      const skill = a.specialist.skill_level;
      let perSpec: number;
      if (role === 'lawyer') perSpec = 0.04;       // -4% par avocat
      else if (role === 'informant') perSpec = 0.03; // -3% par indic
      else perSpec = 0.05;                           // comptable -5%
      coef *= (1 - perSpec * skill / 10);
    }
    return coef;
  }

  /** Réduction effective (0..1) cumulée pour un joueur (player + gang + cartel). */
  static async getCombinedModifier(role: SpecialistRole, playerId: string, gangId: string | null, cartelId: string | null): Promise<number> {
    let coef = 1;
    coef *= await SpecialistService.getModifier('player', playerId, role);
    if (gangId) coef *= await SpecialistService.getModifier('gang', gangId, role);
    if (cartelId) coef *= await SpecialistService.getModifier('cartel', cartelId, role);
    return coef;
  }

  // ──────────────────────────────────────────────────────────
  // CRON : paiement quotidien
  // ──────────────────────────────────────────────────────────

  /** Payeur déduit des fonds de l'owner. Si pas assez, marque inactif. */
  static async paySalaries(): Promise<{ paid: number; defaulted: number; total_paid: number }> {
    const due = await attRepo().find({
      where: { is_active: true },
      relations: ['specialist'],
    });
    const now = new Date();
    const eligible = due.filter(a => !a.next_payment_due || new Date(a.next_payment_due) <= now);

    let paid = 0, defaulted = 0, totalPaid = 0;

    for (const a of eligible) {
      const effectiveDaily = Math.round(a.specialist.salary_daily * (1 - Number(a.discount_pct) / 100) / 10) * 10;
      const debited = await SpecialistService.debitOwner(a.owner_type, a.owner_id, effectiveDaily);

      if (debited) {
        a.last_paid_at = now;
        const next = new Date(now);
        next.setUTCHours(next.getUTCHours() + 24);
        a.next_payment_due = next;
        await attRepo().save(a);
        paid++;
        totalPaid += effectiveDaily;
      } else {
        a.is_active = false;
        a.fired_at = now;
        a.inactive_reason = 'unpaid';
        await attRepo().save(a);
        defaulted++;
        // Notifier
        await SpecialistService.notifyOwner(a.owner_type, a.owner_id,
          'Spécialiste démissionnaire',
          `${a.specialist.name} a démissionné : fonds insuffisants pour le salaire (${effectiveDaily} ∞/jour).`,
        );
      }
    }

    return { paid, defaulted, total_paid: totalPaid };
  }

  private static async debitOwner(ownerType: SpecialistOwnerType, ownerId: string, amount: number): Promise<boolean> {
    if (ownerType === 'player') {
      const b = await balancesRepo().findOneBy({ player_id: ownerId });
      if (!b) return false;
      const shadow = Number(b.infinite_shadow);
      const light = Number(b.infinite_light);
      if (shadow + light < amount) return false;
      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();
      return true;
    }
    if (ownerType === 'gang') {
      const g = await gangRepo().findOneBy({ id: ownerId });
      if (!g) return false;
      const ts = Number(g.treasury_shadow);
      const tl = Number(g.treasury_light);
      if (ts + tl < amount) return false;
      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 true;
    }
    if (ownerType === 'cartel') {
      const c = await cartelRepo().findOneBy({ id: ownerId });
      if (!c) return false;
      const ts = Number(c.treasury_shadow);
      const tl = Number(c.treasury_light);
      if (ts + tl < amount) return false;
      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 true;
    }
    return false;
  }

  private static async notifyOwner(ownerType: SpecialistOwnerType, ownerId: string, title: string, message: string): Promise<void> {
    if (ownerType === 'player') {
      await notifRepo().save(notifRepo().create({ player_id: ownerId, type: 'specialist', title, message }));
    }
    // Gang / Cartel : notifier le leader / admin
    // (simplifié pour premier jet)
  }
}
