import { AppDataSource } from '../config/database';
import { GangMission, GangMissionTemplate } from '../models/GangMission';
import { Player } from '../models/Player';
import { GangMember } from '../models/GangMember';
import { Gang } from '../models/Gang';
import { Notification } from '../models/Notification';
import { GangService } from './gang.service';
import { TransactionService } from './transaction.service';
import { MissionEngineService } from './mission-engine.service';

const templateRepo = () => AppDataSource.getRepository(GangMissionTemplate);
const missionRepo = () => AppDataSource.getRepository(GangMission);
const playerRepo = () => AppDataSource.getRepository(Player);
const gangMemberRepo = () => AppDataSource.getRepository(GangMember);
const gangRepo = () => AppDataSource.getRepository(Gang);
const notifRepo = () => AppDataSource.getRepository(Notification);

/**
 * Missions gang (Marcello / RépubliVain / Mara Gracia / Fourbe Bétonnerie).
 * Pattern similaire à MissionService (timer + choix A/B/C). Le joueur doit être
 * membre du gang NPC pour démarrer. XP + argent + chaleur récompensés selon
 * le choix. Historique conservé.
 */
export class GangMissionService {

  static async listAvailable(playerId: string, gangId: string): Promise<any[]> {
    const gm = await gangMemberRepo().findOne({ where: { player_id: playerId, gang_id: gangId } });
    if (!gm) return [];

    const gang = await gangRepo().findOneBy({ id: gangId });
    if (!gang?.gang_code) return [];

    const allForGang = await templateRepo().find({
      where: { gang_code: gang.gang_code, is_active: true },
      order: { mission_order: 'ASC' },
    });
    const completed = new Set(
      (await missionRepo().find({
        where: { player_id: playerId, gang_id: gangId, status: 'completed' },
      })).map(m => m.template_code),
    );
    const inProgress = await missionRepo().find({
      where: { player_id: playerId, gang_id: gangId, status: 'in_progress' },
    });

    const playerGrade = GangService.computeMemberGrade(Number((await playerRepo().findOneBy({ id: playerId }))?.experience || 0));

    return allForGang.map(t => {
      const prereqOk = !t.prerequisites_codes || t.prerequisites_codes.every(c => completed.has(c));
      const gradeOk = playerGrade >= t.requires_grade;
      const done = completed.has(t.code);
      const current = inProgress.find(m => m.template_code === t.code);
      return {
        code: t.code,
        name: t.name,
        description: t.description,
        narrative: t.narrative_context,
        act: t.act,
        order: t.mission_order,
        xp_reward: t.xp_reward,
        money_light: t.money_reward_light,
        money_shadow: t.money_reward_shadow,
        heat_delta: t.heat_delta,
        requires_grade: t.requires_grade,
        duration_minutes: t.duration_minutes,
        status: done ? 'completed' : current ? 'in_progress' : (prereqOk && gradeOk) ? 'available' : 'locked',
        locked_reasons: (prereqOk && gradeOk) ? [] : [
          ...(prereqOk ? [] : ['Prérequis mission manquants']),
          ...(gradeOk ? [] : [`Grade ${t.requires_grade} requis`]),
        ],
        mission_id: current?.id,
        completes_at: current?.completes_at,
        choices: { A: t.choice_a, B: t.choice_b, C: t.choice_c },
      };
    });
  }

  static async start(playerId: string, gangId: string, templateCode: string): Promise<GangMission> {
    const template = await templateRepo().findOneBy({ code: templateCode });
    if (!template) throw new Error('Template mission introuvable');
    // Vérifier pas déjà en cours
    const active = await missionRepo().findOne({
      where: { player_id: playerId, gang_id: gangId, status: 'in_progress' },
    });
    if (active) throw new Error('Vous avez déjà une mission gang en cours');

    const now = new Date();
    const completesAt = new Date(now.getTime() + template.duration_minutes * 60000);
    const m = missionRepo().create({
      player_id: playerId,
      gang_id: gangId,
      template_code: templateCode,
      status: 'in_progress',
      started_at: now,
      completes_at: completesAt,
    });
    return missionRepo().save(m);
  }

  static async resolve(playerId: string, missionId: string, choice: 'A' | 'B' | 'C'): Promise<{
    mission: GangMission; rewards: any;
  }> {
    const m = await missionRepo().findOneBy({ id: missionId });
    if (!m) throw new Error('Mission introuvable');
    if (m.player_id !== playerId) throw new Error('Pas votre mission');
    if (m.status !== 'in_progress') throw new Error('Mission non active');
    if (m.completes_at && new Date(m.completes_at) > new Date()) {
      throw new Error('Mission pas encore terminée');
    }

    const template = await templateRepo().findOneBy({ code: m.template_code });
    if (!template) throw new Error('Template introuvable');

    // Base rewards
    let xp = template.xp_reward;
    let light = template.money_reward_light;
    let shadow = template.money_reward_shadow;
    let heat = template.heat_delta;
    let outcomeText = choice === 'A' ? template.outcome_a : choice === 'B' ? template.outcome_b : template.outcome_c;

    // Modulation selon choix (A: bonus / B: standard / C: malus)
    if (choice === 'A') { xp = Math.round(xp * 1.1); }
    else if (choice === 'C') { xp = Math.round(xp * 0.7); heat = Math.round(heat * 1.2); }

    m.status = 'completed';
    m.completed_at = new Date();
    m.choice = choice;
    m.outcome_summary = outcomeText;
    m.rewards = { xp, money_light: light, money_shadow: shadow, heat };
    await missionRepo().save(m);

    // Phase 16 (2026-04-22) — délègue à MissionEngineService (pattern
    // commun U8). Fix du bug historique : le `heat` n'incrémentait JAMAIS
    // `player_gauges.chaleur` — il n'était que loggé dans heat_events sans
    // effet. Maintenant via HeatService la chaleur est bien mise à jour.
    await MissionEngineService.applyStandardRewards(playerId, {
      xp,
      money_light: light,
      money_shadow: shadow,
    });
    if (heat !== 0) {
      await MissionEngineService.applyHeatDelta(
        playerId, heat,
        `gang_mission_${template.code}`, 'gang_mission',
      );
    }

    await TransactionService.log({
      player_id: playerId, category: 'gang_mission', type: 'in',
      amount: light + shadow, currency: 'infinite_shadow',
      description: `Mission gang ${template.name} (choix ${choice})`,
    });

    await notifRepo().save(notifRepo().create({
      player_id: playerId,
      type: 'gang_mission',
      title: `Mission gang terminée : ${template.name}`,
      message: outcomeText || 'Résultat obtenu.',
    }));

    return { mission: m, rewards: { xp, light, shadow, heat } };
  }

  static async activeMission(playerId: string, gangId: string): Promise<GangMission | null> {
    return missionRepo().findOne({
      where: { player_id: playerId, gang_id: gangId, status: 'in_progress' },
    });
  }

  static async history(playerId: string, gangId: string, limit = 50): Promise<GangMission[]> {
    return missionRepo().find({
      where: { player_id: playerId, gang_id: gangId, status: 'completed' },
      order: { completed_at: 'DESC' },
      take: limit,
    });
  }
}
