import { AppDataSource } from '../config/database';
import { LessThan } from 'typeorm';
import { Cartel } from '../models/Cartel';
import { CartelTerritory } from '../models/CartelTerritory';
import { CartelMember } from '../models/CartelMember';
import { Gang } from '../models/Gang';
import { GangMember } from '../models/GangMember';
import { Notification } from '../models/Notification';

const cartelRepo = () => AppDataSource.getRepository(Cartel);
const terRepo = () => AppDataSource.getRepository(CartelTerritory);
const memberRepo = () => AppDataSource.getRepository(CartelMember);
const gangRepo = () => AppDataSource.getRepository(Gang);
const gangMemberRepo = () => AppDataSource.getRepository(GangMember);
const notifRepo = () => AppDataSource.getRepository(Notification);

/**
 * Points de Territoire d'un cartel. Création, assignation, perte, heal.
 */
export class CartelTerritoryService {
  static readonly REASSIGN_DEADLINE_DAYS = 7;
  static readonly HEAL_PER_HOUR = 10;
  static readonly MAX_HP = 1000;

  /** Assigner un nouveau Point de Territoire (création ou remplacement). */
  static async assign(playerId: string, cartelId: string, lat: number, lng: number, name?: string): Promise<CartelTerritory> {
    // Vérifier que le joueur est admin du cartel
    const isAdmin = await CartelTerritoryService.isAdmin(playerId, cartelId);
    if (!isAdmin) throw new Error('Seul un administrateur du cartel peut assigner un Point de Territoire');

    const cartel = await cartelRepo().findOneBy({ id: cartelId });
    if (!cartel) throw new Error('Cartel introuvable');

    // Premier territoire du cartel → marqué is_origin
    const existing = await terRepo().find({ where: { cartel_id: cartelId, lost_at: null as any } });
    const isFirst = existing.length === 0;

    const territory = terRepo().create({
      cartel_id: cartelId,
      lat,
      lng,
      name: name || (isFirst ? `${cartel.name} — Origine` : `${cartel.name} — Annexe ${existing.length + 1}`),
      hp: CartelTerritoryService.MAX_HP,
      hp_max: CartelTerritoryService.MAX_HP,
      is_origin: isFirst,
    });
    const saved = await terRepo().save(territory);

    // Lever le delai de réassignation
    if (cartel.territory_lost_at) {
      await cartelRepo().update(cartelId, { territory_lost_at: null });
    }

    return saved;
  }

  /** Marquer un territoire comme perdu. Si plus aucun actif → notification + deadline 7j. */
  static async markLost(territoryId: string, reason: 'attacked' | 'police_seized' | 'abandoned'): Promise<void> {
    const ter = await terRepo().findOneBy({ id: territoryId });
    if (!ter) return;
    ter.lost_at = new Date();
    await terRepo().save(ter);

    const remaining = await terRepo().count({ where: { cartel_id: ter.cartel_id, lost_at: null as any } });
    if (remaining === 0) {
      await CartelTerritoryService.triggerReassignDeadline(ter.cartel_id, reason);
    }
  }

  /** Déclenche le flot "cartel sans territoire" : notification + lightbox + deadline 7j. */
  static async triggerReassignDeadline(cartelId: string, reason: string): Promise<void> {
    const cartel = await cartelRepo().findOneBy({ id: cartelId });
    if (!cartel) return;

    await cartelRepo().update(cartelId, {
      territory_lost_at: new Date(),
    });

    const msg = reason === 'attacked'
      ? "Votre cartel a perdu son territoire : assigner un nouveau."
      : reason === 'police_seized'
        ? "Votre cartel a perdu son territoire suite à un raid GIGN."
        : "Votre cartel n'a plus de territoire actif.";

    const body = "Suite à l'attaque de votre territoire, les possessions de votre Cartel ont été saisies, hormis ses achats en nom propre. Les gangsters bossent maintenant tous pour votre rival, et il va falloir vous assurer de si vos membres ont tourné la veste, ou sont toujours à vos côtés.\n\nParfait, les pentes se remontent… pour commencer, il faut choisir un le point pour un nouveau départ.";

    // Notifier les admins
    const admins = await memberRepo().find({ where: { cartel_id: cartelId, is_admin: true, status: 'active' } });
    for (const a of admins) {
      const gang = await gangRepo().findOneBy({ id: a.gang_id });
      if (gang) {
        await notifRepo().save(notifRepo().create({
          player_id: gang.leader_id,
          type: 'cartel_territory_lost',
          title: msg,
          message: body,
          link: `/play?cartel=${cartelId}&action=assign_territory`,
        }));
      }
    }
  }

  /** CRON : dissout les cartels qui n'ont pas réassigné sous 7 jours. */
  static async enforceReassignDeadline(): Promise<{ dissolved: number }> {
    const deadline = new Date(Date.now() - CartelTerritoryService.REASSIGN_DEADLINE_DAYS * 24 * 3600 * 1000);
    const expired = await cartelRepo().find({
      where: {
        is_active: true,
        territory_lost_at: LessThan(deadline),
      },
    });
    let dissolved = 0;
    for (const c of expired) {
      const still = await terRepo().count({ where: { cartel_id: c.id, lost_at: null as any } });
      if (still > 0) {
        // Territoire re-assigné entre-temps
        await cartelRepo().update(c.id, { territory_lost_at: null });
        continue;
      }
      // Dissolution auto
      await cartelRepo().update(c.id, {
        is_active: false,
        dissolved_at: new Date(),
      });
      await memberRepo().update({ cartel_id: c.id }, { status: 'left' });
      dissolved++;
    }
    return { dissolved };
  }

  /** CRON heal : +10 HP/h jusqu'à max_hp. */
  static async healAll(): Promise<{ healed: number }> {
    const territories = await terRepo().find({ where: { lost_at: null as any } });
    let healed = 0;
    for (const t of territories) {
      if (t.hp >= t.hp_max) continue;
      const newHp = Math.min(t.hp_max, t.hp + CartelTerritoryService.HEAL_PER_HOUR);
      await terRepo().update(t.id, { hp: newHp, last_heal_at: new Date() });
      healed++;
    }
    return { healed };
  }

  static async listForCartel(cartelId: string): Promise<CartelTerritory[]> {
    return terRepo().find({
      where: { cartel_id: cartelId, lost_at: null as any },
      order: { is_origin: 'DESC', created_at: 'ASC' },
    });
  }

  static async damageTerritory(territoryId: string, dmg: number): Promise<{ hp: number; destroyed: boolean }> {
    const t = await terRepo().findOneBy({ id: territoryId });
    if (!t) throw new Error('Territoire introuvable');
    const newHp = Math.max(0, t.hp - dmg);
    t.hp = newHp;
    await terRepo().save(t);
    if (newHp === 0) {
      await CartelTerritoryService.markLost(territoryId, 'attacked');
      return { hp: 0, destroyed: true };
    }
    return { hp: newHp, destroyed: false };
  }

  private static async isAdmin(playerId: string, cartelId: string): Promise<boolean> {
    const gm = await gangMemberRepo().findOne({ where: { player_id: playerId } });
    if (!gm) return false;
    const cm = await memberRepo().findOne({
      where: { gang_id: gm.gang_id, cartel_id: cartelId, is_admin: true, status: 'active' },
    });
    return !!cm;
  }
}
