import { AppDataSource } from '../config/database';
import { Cartel } from '../models/Cartel';
import { CartelMember } from '../models/CartelMember';
import { CartelAsset } from '../models/CartelAsset';
import { CartelTakeover, CartelInvitation } from '../models/CartelInvitation';
import { Gang } from '../models/Gang';
import { GangMember } from '../models/GangMember';
import { Player } from '../models/Player';
import { Notification } from '../models/Notification';
import { PlayerCartelHistory } from '../models/PlayerHistory';
import { CartelTerritoryService } from './cartel-territory.service';

const cartelRepo = () => AppDataSource.getRepository(Cartel);
const memberRepo = () => AppDataSource.getRepository(CartelMember);
const assetRepo = () => AppDataSource.getRepository(CartelAsset);
const takeoverRepo = () => AppDataSource.getRepository(CartelTakeover);
const invitationRepo = () => AppDataSource.getRepository(CartelInvitation);
const gangRepo = () => AppDataSource.getRepository(Gang);
const gangMemberRepo = () => AppDataSource.getRepository(GangMember);
const playerRepo = () => AppDataSource.getRepository(Player);
const notifRepo = () => AppDataSource.getRepository(Notification);
const cartelHistoryRepo = () => AppDataSource.getRepository(PlayerCartelHistory);

/**
 * Prise de contrôle d'un cartel par un joueur (via victoire sur son territoire).
 *
 * Cas A : attaquant a déjà un cartel (monté ou membre).
 *   → Toutes les possessions (gangsters, armes, véhicules non planqués, trésorerie,
 *     racket zones, commerces illégaux) passent à son cartel.
 *   → Point de Territoire reste à l'ancien admin (il peut continuer à défendre).
 *   → Lightbox "Vous avez pris le contrôle du cartel de {name}…"
 *   → Invitation optionnelle aux membres du cartel battu de rejoindre l'attaquant.
 *
 * Cas B : attaquant n'a pas de cartel.
 *   → Il devient l'unique administrateur du cartel.
 *   → Autres admins deviennent simples membres.
 *   → Lightbox "Vous avez pris le contrôle du Cartel {name}…" +
 *     choix "Sortir tout le monde" / "Discuter".
 */
export class CartelTakeoverService {

  static async takeover(
    attackerPlayerId: string,
    targetCartelId: string,
    territoryId: string | null,
  ): Promise<{ case: 'A' | 'B'; takeover_id: string; summary: any }> {
    const targetCartel = await cartelRepo().findOneBy({ id: targetCartelId });
    if (!targetCartel) throw new Error('Cartel cible introuvable');

    // Déterminer si l'attaquant est déjà dans un cartel (cas A) ou non (cas B)
    const attackerGm = await gangMemberRepo().findOne({ where: { player_id: attackerPlayerId } });
    const attackerCartelMember = attackerGm
      ? await memberRepo().findOne({ where: { gang_id: attackerGm.gang_id, status: 'active' } })
      : null;

    // Phase 17.2 finition Gap 6 (2026-05-06) — Pacte de non-aggression cartel.
    // Un cartel allié (status=accepted) ne peut pas être pris d'assaut par
    // l'autre. La cohérence narrative : c'est précisément la raison d'être
    // d'une alliance.
    if (attackerCartelMember) {
      const { CartelAllianceService } = await import('./cartel-alliance.service');
      const allied = await CartelAllianceService.areAllies(
        attackerCartelMember.cartel_id,
        targetCartelId,
      );
      if (allied) {
        throw new Error('Vos cartels sont alliés — pacte de non-aggression actif. Takeover refusé.');
      }
    }

    if (attackerCartelMember) {
      return CartelTakeoverService.caseA(attackerPlayerId, attackerCartelMember.cartel_id, targetCartelId, territoryId);
    }
    return CartelTakeoverService.caseB(attackerPlayerId, targetCartelId, territoryId);
  }

  /** Cas A : transfert possessions, Point de Territoire reste à l'ancien admin. */
  static async caseA(
    attackerPlayerId: string,
    attackerCartelId: string,
    targetCartelId: string,
    territoryId: string | null,
  ): Promise<{ case: 'A'; takeover_id: string; summary: any }> {
    const targetCartel = await cartelRepo().findOneBy({ id: targetCartelId });
    if (!targetCartel) throw new Error('Cartel cible introuvable');

    // Transférer assets
    const assets = await assetRepo().find({ where: { cartel_id: targetCartelId } });
    let transferredCount = 0;
    for (const a of assets) {
      // Skip hideouts (planqués)
      if (a.asset_type === 'hideout') continue;
      a.cartel_id = attackerCartelId;
      await assetRepo().save(a);
      transferredCount++;
    }

    // Transférer trésorerie
    const light = Number(targetCartel.treasury_light) || 0;
    const shadow = Number(targetCartel.treasury_shadow) || 0;
    await cartelRepo().createQueryBuilder().update()
      .set({
        treasury_light: () => `treasury_light + ${light}`,
        treasury_shadow: () => `treasury_shadow + ${shadow}`,
      })
      .where('id = :id', { id: attackerCartelId })
      .execute();
    await cartelRepo().update(targetCartelId, { treasury_light: 0, treasury_shadow: 0 });

    // Marquer Point de Territoire saisi (mais reste à l'ancien admin — il peut défendre la nouvelle fois)
    // → on ne déplace pas le territoire, on le marque endommagé.
    if (territoryId) {
      await CartelTerritoryService.damageTerritory(territoryId, 1000);
    }

    const takeover = await takeoverRepo().save(takeoverRepo().create({
      cartel_id: targetCartelId,
      cartel_name: targetCartel.name,
      attacker_player_id: attackerPlayerId,
      attacker_cartel_id: attackerCartelId,
      took_over_case: 'A',
      territory_id: territoryId,
      assets_transferred: transferredCount,
      money_transferred_light: light,
      money_transferred_shadow: shadow,
    }));

    // Notifier les membres du cartel battu
    await CartelTakeoverService.notifyAllMembers(
      targetCartelId,
      'Attaque subie',
      `Votre cartel a été attaqué. Possessions saisies. Le Point de Territoire a résisté.`,
    );

    // Inviter les membres du cartel battu à rejoindre l'attaquant (cas A extension PS utilisateur)
    await CartelTakeoverService.inviteDefeatedMembers(attackerPlayerId, attackerCartelId, targetCartelId);

    // Phase 6 markers (2026-05-07) — déclenche l'état 'conqueror' 60s sur l'avatar.
    await playerRepo().update(attackerPlayerId, { last_territory_won_at: new Date() });

    return { case: 'A', takeover_id: takeover.id, summary: { transferred: transferredCount, light, shadow } };
  }

  /** Cas B : attaquant devient unique admin. */
  static async caseB(
    attackerPlayerId: string,
    targetCartelId: string,
    territoryId: string | null,
  ): Promise<{ case: 'B'; takeover_id: string; summary: any }> {
    const targetCartel = await cartelRepo().findOneBy({ id: targetCartelId });
    if (!targetCartel) throw new Error('Cartel cible introuvable');

    // L'attaquant doit avoir un gang pour devenir admin (via CartelMember)
    const attackerGm = await gangMemberRepo().findOne({ where: { player_id: attackerPlayerId } });
    if (!attackerGm) throw new Error('Vous devez faire partie d\'un gang');

    // Rétrograder tous les admins actuels
    await memberRepo().update({ cartel_id: targetCartelId, is_admin: true }, { is_admin: false });

    // Ajouter l'attaquant comme admin unique
    const existing = await memberRepo().findOne({ where: { cartel_id: targetCartelId, gang_id: attackerGm.gang_id } });
    if (existing) {
      existing.is_admin = true;
      existing.is_officer = true;
      existing.status = 'active';
      existing.primary_player_id = attackerPlayerId;
      await memberRepo().save(existing);
    } else {
      await memberRepo().save(memberRepo().create({
        cartel_id: targetCartelId,
        gang_id: attackerGm.gang_id,
        status: 'active',
        is_admin: true,
        is_officer: true,
        primary_player_id: attackerPlayerId,
      }));
    }

    // Déplacer leader_gang vers le gang de l'attaquant
    await cartelRepo().update(targetCartelId, {
      leader_gang_id: attackerGm.gang_id,
    });

    const takeover = await takeoverRepo().save(takeoverRepo().create({
      cartel_id: targetCartelId,
      cartel_name: targetCartel.name,
      attacker_player_id: attackerPlayerId,
      took_over_case: 'B',
      territory_id: territoryId,
    }));

    await CartelTakeoverService.notifyAllMembers(
      targetCartelId,
      'Cartel pris par un nouveau chef',
      `Le cartel ${targetCartel.name} est maintenant dirigé par un nouvel administrateur.`,
    );

    // Phase 6 markers (2026-05-07) — déclenche l'état 'conqueror' 60s sur l'avatar.
    await playerRepo().update(attackerPlayerId, { last_territory_won_at: new Date() });

    return { case: 'B', takeover_id: takeover.id, summary: {} };
  }

  /** Cas B decision : "Sortir tout le monde" → exclut tous les membres sauf le nouveau admin. */
  static async kickAllMembers(attackerPlayerId: string, cartelId: string): Promise<{ kicked: number }> {
    const gm = await gangMemberRepo().findOne({ where: { player_id: attackerPlayerId } });
    if (!gm) throw new Error('Pas dans un gang');

    const members = await memberRepo().find({ where: { cartel_id: cartelId, status: 'active' } });
    let kicked = 0;
    for (const m of members) {
      if (m.gang_id === gm.gang_id) continue;
      await memberRepo().update({ cartel_id: cartelId, gang_id: m.gang_id }, { status: 'left' });
      // Historique
      const gang = await gangRepo().findOneBy({ id: m.gang_id });
      if (gang) {
        const leader = await playerRepo().findOneBy({ id: gang.leader_id });
        if (leader) {
          await cartelHistoryRepo().save(cartelHistoryRepo().create({
            player_id: leader.id,
            cartel_id: cartelId,
            cartel_name: (await cartelRepo().findOneBy({ id: cartelId }))?.name || '?',
            joined_at: m.joined_at,
            left_at: new Date(),
            leave_reason: 'takeover',
            was_admin: m.is_admin,
          }));
        }
      }
      kicked++;
    }
    await cartelRepo().update(cartelId, { gang_count: 1 });

    await takeoverRepo().createQueryBuilder().update()
      .set({ decision: 'kick_all' })
      .where('cartel_id = :id AND attacker_player_id = :pid', { id: cartelId, pid: attackerPlayerId })
      .execute();

    return { kicked };
  }

  /** Cas B decision : "Discuter" → laisse les membres en place, on espère leur loyauté. */
  static async discussWithMembers(attackerPlayerId: string, cartelId: string): Promise<void> {
    await takeoverRepo().createQueryBuilder().update()
      .set({ decision: 'discuss' })
      .where('cartel_id = :id AND attacker_player_id = :pid', { id: cartelId, pid: attackerPlayerId })
      .execute();
    await CartelTakeoverService.notifyAllMembers(cartelId, 'Nouveau chef',
      'Votre nouveau chef souhaite discuter avec vous de la suite. Restez ou quittez : le choix vous appartient.');
  }

  /** Invitation aux membres du cartel battu (si attaquant avait déjà un cartel). */
  static async inviteDefeatedMembers(
    attackerPlayerId: string,
    attackerCartelId: string,
    targetCartelId: string,
  ): Promise<{ invitations: number }> {
    const members = await memberRepo().find({ where: { cartel_id: targetCartelId, status: 'active' } });
    let invitations = 0;
    const expiresAt = new Date(Date.now() + 7 * 24 * 3600 * 1000);
    for (const m of members) {
      const gang = await gangRepo().findOneBy({ id: m.gang_id });
      if (!gang) continue;
      const leader = gang.leader_id;
      await invitationRepo().save(invitationRepo().create({
        cartel_id: attackerCartelId,
        invitee_player_id: leader,
        invited_by_player_id: attackerPlayerId,
        context: 'takeover',
        status: 'pending',
        expires_at: expiresAt,
        message: 'Votre ancien cartel a été battu. Rejoignez-nous plutôt que de repartir seul.',
      }));
      await notifRepo().save(notifRepo().create({
        player_id: leader,
        type: 'cartel_invitation',
        title: 'Invitation cartel',
        message: `Vous avez été invité à rejoindre un cartel après la chute du vôtre. 7 jours pour accepter.`,
      }));
      invitations++;
    }
    return { invitations };
  }

  private static async notifyAllMembers(cartelId: string, title: string, message: string): Promise<void> {
    const members = await memberRepo().find({ where: { cartel_id: cartelId, status: 'active' } });
    for (const m of members) {
      const gang = await gangRepo().findOneBy({ id: m.gang_id });
      if (gang) {
        await notifRepo().save(notifRepo().create({
          player_id: gang.leader_id, type: 'cartel', title, message,
        }));
      }
    }
  }
}
