/**
 * CartelAllianceService — gestion des alliances entre cartels.
 *
 * Workflow :
 *   1. Admin cartel A → propose alliance à cartel B (status=pending)
 *   2. Admin cartel B reçoit notification persistante "alliance_proposal"
 *   3. Admin cartel B → accept (status=accepted) ou reject (status=rejected)
 *   4. Admin cartel A reçoit notification "alliance_accepted" ou "alliance_rejected"
 *
 * Conséquences d'une alliance 'accepted' :
 *   - Points de territoire vus entre eux en VERT FONCÉ (#166534) via visibility.service
 *   - Helper `areAllies(c1, c2)` exposé pour autres services
 *
 * Règles :
 *   - L'action "propose/accept/reject/cancel" requiert d'être ADMIN du cartel source
 *     (CartelMember.is_admin=true, status='active') OU leader du leader_gang du cartel.
 *   - 1 seule proposition pending par paire (sens unique).
 *   - Si A propose à B et B a déjà proposé à A (pending) : A peut directement accepter.
 */

import { AppDataSource } from '../config/database';
import { CartelAlliance, CartelAllianceStatus } from '../models/CartelAlliance';
import { CartelMember } from '../models/CartelMember';
import { Cartel } from '../models/Cartel';
import { Gang } from '../models/Gang';
import { Notification } from '../models/Notification';

const allianceRepo = () => AppDataSource.getRepository(CartelAlliance);
const memberRepo = () => AppDataSource.getRepository(CartelMember);
const cartelRepo = () => AppDataSource.getRepository(Cartel);
const gangRepo = () => AppDataSource.getRepository(Gang);
const notifRepo = () => AppDataSource.getRepository(Notification);

export class CartelAllianceService {

  /** Retourne le cartelId si le joueur est admin d'un cartel, sinon null. */
  static async getAdminCartelId(playerId: string): Promise<string | null> {
    // 1. Check membre admin via CartelMember
    const adminMember = await memberRepo().findOne({
      where: { primary_player_id: playerId, is_admin: true, status: 'active' },
    });
    if (adminMember) return adminMember.cartel_id;

    // 2. Fallback : leader du leader_gang (créateur initial)
    const playerGang = await gangRepo().findOne({ where: { leader_id: playerId } });
    if (!playerGang) return null;
    const cartel = await cartelRepo().findOne({ where: { leader_gang_id: playerGang.id, is_active: true } });
    return cartel?.id ?? null;
  }

  /** Proposer une alliance au cartel cible. Requiert d'être admin de son propre cartel. */
  static async propose(playerId: string, targetCartelId: string): Promise<CartelAlliance> {
    const sourceCartelId = await this.getAdminCartelId(playerId);
    if (!sourceCartelId) throw new Error('Vous n\'êtes pas admin d\'un cartel');
    if (sourceCartelId === targetCartelId) throw new Error('Impossible de s\'allier à soi-même');

    const target = await cartelRepo().findOne({ where: { id: targetCartelId, is_active: true } });
    if (!target) throw new Error('Cartel cible introuvable');

    // Existing alliance (accepted) → already allied
    const existing = await allianceRepo()
      .createQueryBuilder('a')
      .where('a.status IN (:...statuses)', { statuses: ['pending', 'accepted'] })
      .andWhere(
        '((a.requester_cartel_id = :c1 AND a.target_cartel_id = :c2) OR (a.requester_cartel_id = :c2 AND a.target_cartel_id = :c1))',
        { c1: sourceCartelId, c2: targetCartelId },
      )
      .getOne();

    if (existing) {
      if (existing.status === 'accepted') throw new Error('Vous êtes déjà alliés');
      // Pending dans l'autre sens → permet auto-accept
      if (existing.target_cartel_id === sourceCartelId) {
        return this.respond(playerId, existing.id, 'accepted');
      }
      throw new Error('Une proposition est déjà en attente');
    }

    // Créer
    const alliance = allianceRepo().create({
      requester_cartel_id: sourceCartelId,
      target_cartel_id: targetCartelId,
      requested_by_player_id: playerId,
      status: 'pending',
    });
    const saved = await allianceRepo().save(alliance);

    // Notifier l'admin du cartel cible (primary_player_id du admin member OU leader du leader_gang)
    const sourceCartel = await cartelRepo().findOneBy({ id: sourceCartelId });
    const targetAdminId = await this.resolveAdminPlayerId(targetCartelId);
    if (targetAdminId && sourceCartel) {
      await notifRepo().save(notifRepo().create({
        player_id: targetAdminId,
        type: 'alliance_proposal',
        title: `Proposition d'alliance — ${sourceCartel.name}`,
        message: `${sourceCartel.name} vous propose une alliance. Acceptez ou refusez.`,
        link: `alliance:${saved.id}`,
      }));
    }

    return saved;
  }

  /** Répondre à une proposition reçue. Requiert d'être admin du cartel cible. */
  static async respond(
    playerId: string,
    allianceId: string,
    action: 'accepted' | 'rejected',
  ): Promise<CartelAlliance> {
    const alliance = await allianceRepo().findOneBy({ id: allianceId });
    if (!alliance) throw new Error('Alliance introuvable');
    if (alliance.status !== 'pending') throw new Error('Cette proposition a déjà été traitée');

    const adminCartelId = await this.getAdminCartelId(playerId);
    if (adminCartelId !== alliance.target_cartel_id) {
      throw new Error('Seul l\'admin du cartel cible peut répondre');
    }

    alliance.status = action;
    alliance.responded_by_player_id = playerId;
    alliance.responded_at = new Date();
    const saved = await allianceRepo().save(alliance);

    // Notifier le requester admin
    const requesterAdminId = await this.resolveAdminPlayerId(alliance.requester_cartel_id);
    const targetCartel = await cartelRepo().findOneBy({ id: alliance.target_cartel_id });
    if (requesterAdminId && targetCartel) {
      const isAccepted = action === 'accepted';
      await notifRepo().save(notifRepo().create({
        player_id: requesterAdminId,
        type: isAccepted ? 'alliance_accepted' : 'alliance_rejected',
        title: isAccepted
          ? `Alliance acceptée par ${targetCartel.name}`
          : `Alliance refusée par ${targetCartel.name}`,
        message: isAccepted
          ? `${targetCartel.name} a accepté votre proposition d'alliance.`
          : `${targetCartel.name} a refusé votre proposition d'alliance.`,
        link: `alliance:${saved.id}`,
      }));
    }

    // Supprimer les notifs alliance_proposal obsolètes (la proposition a été répondue)
    await notifRepo()
      .createQueryBuilder()
      .delete()
      .where("type = 'alliance_proposal' AND link = :link", { link: `alliance:${allianceId}` })
      .execute();

    return saved;
  }

  /** Annuler sa propre proposition pending. Requiert d'être admin du cartel source. */
  static async cancel(playerId: string, allianceId: string): Promise<CartelAlliance> {
    const alliance = await allianceRepo().findOneBy({ id: allianceId });
    if (!alliance) throw new Error('Alliance introuvable');
    if (alliance.status !== 'pending') throw new Error('Non annulable : proposition déjà traitée');

    const adminCartelId = await this.getAdminCartelId(playerId);
    if (adminCartelId !== alliance.requester_cartel_id) {
      throw new Error('Seul l\'admin du cartel proposant peut annuler');
    }

    alliance.status = 'cancelled';
    alliance.cancelled_at = new Date();
    const saved = await allianceRepo().save(alliance);

    // Supprimer les notifs alliance_proposal de l'ancien target
    await notifRepo()
      .createQueryBuilder()
      .delete()
      .where("type = 'alliance_proposal' AND link = :link", { link: `alliance:${allianceId}` })
      .execute();

    return saved;
  }

  /** Rompre une alliance active. Requiert d'être admin d'un des 2 cartels. */
  static async breakAlliance(playerId: string, allianceId: string): Promise<CartelAlliance> {
    const alliance = await allianceRepo().findOneBy({ id: allianceId });
    if (!alliance) throw new Error('Alliance introuvable');
    if (alliance.status !== 'accepted') throw new Error('Non rompable : alliance inactive');

    const adminCartelId = await this.getAdminCartelId(playerId);
    if (adminCartelId !== alliance.requester_cartel_id && adminCartelId !== alliance.target_cartel_id) {
      throw new Error('Vous devez être admin d\'un des cartels alliés');
    }

    // Phase 17.2 finition Gap 3 (2026-05-06) — Statut dédié 'broken' au lieu
    // de 'cancelled' (réservé à l'annulation pré-acceptation). Trace qui a
    // rompu et quand pour l'historique diplomatique.
    alliance.status = 'broken';
    alliance.broken_at = new Date();
    alliance.broken_by_player_id = playerId;
    return allianceRepo().save(alliance);
  }

  /**
   * Phase 17.2 finition Gap 5 (2026-05-06) — Auto-reject des propositions
   * pending vieilles de plus de 7 jours. Évite les tickets diplomatiques
   * fantômes qui restent éternellement.
   *
   * Pour chaque proposition expirée :
   *   • status='rejected', responded_at=NOW, responded_by_player_id=NULL
   *   • Notification au proposant : "Votre proposition à <cartel> a expiré"
   *
   * Appelé par cron toutes les heures (cf server.ts).
   */
  static async expirePendingProposals(): Promise<{ expired: number }> {
    const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
    const expired = await allianceRepo()
      .createQueryBuilder('a')
      .where('a.status = :s', { s: 'pending' })
      .andWhere('a.requested_at < :cutoff', { cutoff: sevenDaysAgo })
      .getMany();

    if (expired.length === 0) return { expired: 0 };

    for (const a of expired) {
      a.status = 'rejected';
      a.responded_at = new Date();
      a.responded_by_player_id = null;
      await allianceRepo().save(a);

      // Notif au proposant
      const targetCartel = await cartelRepo().findOneBy({ id: a.target_cartel_id });
      const targetName = targetCartel?.name ?? '(cartel inconnu)';
      try {
        await notifRepo().save(notifRepo().create({
          player_id: a.requested_by_player_id,
          type: 'system',
          title: 'Proposition d\'alliance expirée',
          message: `Votre proposition d'alliance avec ${targetName} a expiré (7 jours sans réponse).`,
          link: `alliance:${a.id}`,
        }));
      } catch { /* silent — notif non critique */ }
    }

    console.log(`[CRON] CartelAlliance: ${expired.length} propositions expirées (auto-reject 7j)`);
    return { expired: expired.length };
  }

  /**
   * Phase 17.2 finition Gap 3 (2026-05-06) — Historique des alliances
   * inactives concernant le cartel du joueur. Inclut rejected, cancelled,
   * broken. Tri par date de fin DESC (broken_at > cancelled_at > responded_at).
   * Utilisé par le tab "Historique" d'AlliancesLightbox.
   */
  static async listHistory(playerId: string): Promise<CartelAlliance[]> {
    const cartelId = await this.getAdminCartelId(playerId);
    if (!cartelId) return [];
    return allianceRepo()
      .createQueryBuilder('a')
      .where('a.status IN (:...ss)', { ss: ['rejected', 'cancelled', 'broken'] })
      .andWhere('(a.requester_cartel_id = :c OR a.target_cartel_id = :c)', { c: cartelId })
      .orderBy(
        'COALESCE(a.broken_at, a.cancelled_at, a.responded_at, a.requested_at)',
        'DESC',
      )
      .limit(50)
      .getMany();
  }

  /** Helper : est-ce que 2 cartels sont alliés (status='accepted') ? */
  static async areAllies(cartelId1: string, cartelId2: string): Promise<boolean> {
    if (cartelId1 === cartelId2) return false; // Same cartel != "allié"
    const row = await allianceRepo()
      .createQueryBuilder('a')
      .where('a.status = :s', { s: 'accepted' })
      .andWhere(
        '((a.requester_cartel_id = :c1 AND a.target_cartel_id = :c2) OR (a.requester_cartel_id = :c2 AND a.target_cartel_id = :c1))',
        { c1: cartelId1, c2: cartelId2 },
      )
      .getOne();
    return !!row;
  }

  /**
   * Phase 17.2 finition (2026-05-06) — Résout le cartel_id d'un joueur via
   * son appartenance gang (GangMember actif → gang membre d'un cartel).
   * Retourne null si le joueur n'est dans aucun gang ou dans un gang
   * non-membre d'un cartel.
   */
  static async getCartelIdForPlayer(playerId: string): Promise<string | null> {
    const { GangMember } = await import('../models/GangMember');
    const gm = await AppDataSource.getRepository(GangMember).findOne({
      where: { player_id: playerId },
      select: ['gang_id'],
    });
    if (!gm?.gang_id) return null;
    const cm = await memberRepo().findOne({
      where: { gang_id: gm.gang_id, status: 'active' },
    });
    return cm?.cartel_id ?? null;
  }

  /**
   * Phase 17.2 finition (Gap 6, 2026-05-06) — Vrai cœur de l'enforcement
   * non-aggression : retourne true si les 2 joueurs sont dans des cartels
   * alliés (status='accepted'). Retourne false si :
   *   • Au moins un joueur n'est dans aucun cartel
   *   • Les deux sont dans le même cartel (déjà géré par "Allié" ailleurs)
   *   • Les deux sont dans des cartels distincts non alliés
   */
  static async arePlayersInAlliedCartels(p1: string, p2: string): Promise<boolean> {
    if (p1 === p2) return false;
    const [c1, c2] = await Promise.all([
      this.getCartelIdForPlayer(p1),
      this.getCartelIdForPlayer(p2),
    ]);
    if (!c1 || !c2) return false;
    if (c1 === c2) return false; // même cartel = pas "allié", c'est interne
    return this.areAllies(c1, c2);
  }

  /** Liste des IDs de cartels alliés à `cartelId`. */
  static async getAlliedCartelIds(cartelId: string): Promise<string[]> {
    const rows = await allianceRepo()
      .createQueryBuilder('a')
      .select('CASE WHEN a.requester_cartel_id = :c THEN a.target_cartel_id ELSE a.requester_cartel_id END', 'ally_id')
      .where('a.status = :s', { s: 'accepted' })
      .andWhere('a.requester_cartel_id = :c OR a.target_cartel_id = :c', { c: cartelId })
      .setParameter('c', cartelId)
      .getRawMany();
    return rows.map(r => r.ally_id);
  }

  /** Propositions reçues en attente (pour admin). */
  static async listIncoming(playerId: string): Promise<CartelAlliance[]> {
    const cartelId = await this.getAdminCartelId(playerId);
    if (!cartelId) return [];
    return allianceRepo().find({
      where: { target_cartel_id: cartelId, status: 'pending' as CartelAllianceStatus },
      order: { requested_at: 'DESC' },
    });
  }

  /** Propositions envoyées en attente (pour admin). */
  static async listOutgoing(playerId: string): Promise<CartelAlliance[]> {
    const cartelId = await this.getAdminCartelId(playerId);
    if (!cartelId) return [];
    return allianceRepo().find({
      where: { requester_cartel_id: cartelId, status: 'pending' as CartelAllianceStatus },
      order: { requested_at: 'DESC' },
    });
  }

  /** Alliances actives du cartel du joueur. */
  static async listActive(playerId: string): Promise<CartelAlliance[]> {
    const cartelId = await this.getAdminCartelId(playerId);
    if (!cartelId) return [];
    return allianceRepo()
      .createQueryBuilder('a')
      .where('a.status = :s', { s: 'accepted' })
      .andWhere('a.requester_cartel_id = :c OR a.target_cartel_id = :c', { c: cartelId })
      .orderBy('a.responded_at', 'DESC')
      .getMany();
  }

  /**
   * Phase 8.8 (2026-04-29) — Récupère une alliance par son UUID.
   * Utilisé pour résoudre une notif `link='alliance:UUID'` côté frontend.
   * Retourne null si non trouvée.
   */
  static async getById(allianceId: string): Promise<CartelAlliance | null> {
    return allianceRepo().findOneBy({ id: allianceId });
  }

  /** Statut entre 2 cartels : 'none' | 'pending_sent' | 'pending_received' | 'allied'. */
  static async statusBetween(
    viewerPlayerId: string,
    otherCartelId: string,
  ): Promise<{ status: 'none' | 'pending_sent' | 'pending_received' | 'allied'; alliance_id?: string }> {
    const selfCartelId = await this.getAdminCartelId(viewerPlayerId);
    if (!selfCartelId || selfCartelId === otherCartelId) return { status: 'none' };

    const row = await allianceRepo()
      .createQueryBuilder('a')
      .where('a.status IN (:...ss)', { ss: ['pending', 'accepted'] })
      .andWhere(
        '((a.requester_cartel_id = :c1 AND a.target_cartel_id = :c2) OR (a.requester_cartel_id = :c2 AND a.target_cartel_id = :c1))',
        { c1: selfCartelId, c2: otherCartelId },
      )
      .getOne();

    if (!row) return { status: 'none' };
    if (row.status === 'accepted') return { status: 'allied', alliance_id: row.id };
    if (row.requester_cartel_id === selfCartelId) return { status: 'pending_sent', alliance_id: row.id };
    return { status: 'pending_received', alliance_id: row.id };
  }

  /** Résout le playerId de l'admin d'un cartel (pour notifications). */
  private static async resolveAdminPlayerId(cartelId: string): Promise<string | null> {
    // 1. Admin CartelMember
    const adminMember = await memberRepo().findOne({
      where: { cartel_id: cartelId, is_admin: true, status: 'active' },
    });
    if (adminMember?.primary_player_id) return adminMember.primary_player_id;

    // 2. Leader du leader_gang
    const cartel = await cartelRepo().findOneBy({ id: cartelId });
    if (!cartel) return null;
    const leaderGang = await gangRepo().findOneBy({ id: cartel.leader_gang_id });
    return leaderGang?.leader_id ?? null;
  }
}
