import { LessThanOrEqual, In } from 'typeorm';
import { AppDataSource } from '../config/database';
import { DealerMission } from '../models/DealerMission';
import { GangMember } from '../models/GangMember';
import { PlayerBalances } from '../models/PlayerBalances';
import { getDealingRate, splitIntoGroups, distributeGroupAnchors } from '../constants/dealing-rates';

const missionRepo = () => AppDataSource.getRepository(DealerMission);
const gangMemberRepo = () => AppDataSource.getRepository(GangMember);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);

const DEFAULT_RETAIL_MULTIPLIER = 5;

interface CreateMissionData {
  gangId: string;
  drugName: string;
  stockAmount: number;
  gangsterIds: string[];
  radiusKm: number;
  durationHours: number;
  centerLat: number;
  centerLon: number;
}

export class DealerMissionService {

  // ── CREATE ──

  static async createMission(playerId: string, data: CreateMissionData): Promise<DealerMission> {
    const rate = getDealingRate(data.drugName);
    if (!rate) throw new Error(`Drogue "${data.drugName}" non dealable`);

    // Validation entrées
    const durationHours = Math.max(1, Math.min(48, Math.round(data.durationHours)));
    const radiusKm = Math.max(0.5, Math.min(5, data.radiusKm));

    if (data.gangsterIds.length < 1 || data.gangsterIds.length > 50) {
      throw new Error('Entre 1 et 50 gangsters requis');
    }

    return AppDataSource.transaction(async (manager) => {
      // Verify inventory stock
      const inventoryRows = await manager.query(
        `SELECT id, quantity FROM player_inventory
         WHERE player_id = $1 AND item_type = 'drug' AND LOWER(item_name) = LOWER($2)
         LIMIT 1`,
        [playerId, data.drugName],
      );
      if (!inventoryRows.length || inventoryRows[0].quantity < data.stockAmount) {
        throw new Error('Stock insuffisant dans l\'inventaire');
      }

      // Reserve stock
      const remaining = inventoryRows[0].quantity - data.stockAmount;
      if (remaining === 0) {
        await manager.query(`DELETE FROM player_inventory WHERE id = $1`, [inventoryRows[0].id]);
      } else {
        await manager.query(`UPDATE player_inventory SET quantity = $1 WHERE id = $2`, [remaining, inventoryRows[0].id]);
      }

      // Validate gangsters belong to gang
      const members = await manager.getRepository(GangMember).find({
        where: data.gangsterIds.map((pid) => ({ gang_id: data.gangId, player_id: pid })),
      });
      if (members.length !== data.gangsterIds.length) {
        throw new Error('Un ou plusieurs gangsters n\'appartiennent pas au gang');
      }

      // Split into groups and distribute anchors
      const groupSizes = splitIntoGroups(data.gangsterIds.length);
      const anchors = distributeGroupAnchors(data.centerLat, data.centerLon, radiusKm, groupSizes.length);

      // Build group objects with gangster assignments
      let gangsterIdx = 0;
      const groups = groupSizes.map((size, i) => {
        const gangsters = data.gangsterIds.slice(gangsterIdx, gangsterIdx + size);
        gangsterIdx += size;
        return {
          size,
          gangsters,
          anchor_lat: anchors[i].lat,
          anchor_lon: anchors[i].lon,
        };
      });

      const now = new Date();
      const endsAt = new Date(now.getTime() + durationHours * 3600_000);

      const mission = manager.getRepository(DealerMission).create({
        player_id: playerId,
        gang_id: data.gangId,
        drug_name: data.drugName,
        drug_unit: rate.unit,
        stock_reserved: data.stockAmount,
        gangster_count: data.gangsterIds.length,
        groups,
        radius_km: radiusKm,
        center_lat: data.centerLat,
        center_lon: data.centerLon,
        duration_hours: durationHours,
        started_at: now,
        ends_at: endsAt,
        status: 'pending' as const,
        revenue_total: 0,
        outcome: {},
      });

      return manager.getRepository(DealerMission).save(mission);
    });
  }

  // ── ACTIVATE PENDING → IN_PROGRESS (CRON) ──

  /**
   * Transition pending → in_progress pour les missions dont started_at est passe.
   * Appele par le CRON toutes les 60s.
   */
  static async activatePendingMissions(): Promise<number> {
    const pending = await missionRepo().find({
      where: { status: 'pending' as const },
    });
    let activated = 0;
    for (const m of pending) {
      if (new Date(m.started_at) <= new Date()) {
        await missionRepo().update(m.id, { status: 'in_progress' });
        activated++;
      }
    }
    return activated;
  }

  // ── RESOLVE (CRON) ──

  static async resolveMission(missionId: string): Promise<DealerMission> {
    return AppDataSource.transaction(async (manager) => {
      const repo = manager.getRepository(DealerMission);
      const mission = await repo.findOneByOrFail({ id: missionId });

      if (mission.status !== 'in_progress') {
        throw new Error(`Mission status "${mission.status}" non resolvable`);
      }

      const rate = getDealingRate(mission.drug_name);
      const quotaPerGangsterPerHour = rate?.quota_per_gangster_per_hour ?? 1;
      const incidentChance = rate?.incident_chance_per_hour ?? 0;

      const groups = mission.groups;
      const groupCount = groups.length || 1;
      let totalSold = 0;
      let totalIncidents = 0;
      const arrestedGangsters: string[] = [];

      for (const group of groups) {
        const capacity = quotaPerGangsterPerHour * group.size * mission.duration_hours;
        const allocation = Math.floor(mission.stock_reserved / groupCount);
        const sold = Math.min(capacity, allocation);
        totalSold += sold;
        group.sold_so_far = sold;

        // Roll incidents
        let groupIncidents = 0;
        for (const gId of group.gangsters) {
          for (let h = 0; h < mission.duration_hours; h++) {
            if (Math.random() < incidentChance) {
              groupIncidents++;
              // 30% chance an incident = arrest
              if (Math.random() < 0.3 && !arrestedGangsters.includes(gId)) {
                arrestedGangsters.push(gId);
              }
            }
          }
        }
        group.incidents = groupIncidents;
        totalIncidents += groupIncidents;
      }

      totalSold = Math.min(totalSold, mission.stock_reserved);
      const unsold = mission.stock_reserved - totalSold;
      const revenue = totalSold * DEFAULT_RETAIL_MULTIPLIER;

      // Credit shadow balance
      if (revenue > 0) {
        await manager.query(
          `UPDATE player_balances SET balance_shadow = balance_shadow + $1 WHERE player_id = $2`,
          [revenue, mission.player_id],
        );
      }

      // Return unsold stock
      if (unsold > 0) {
        const existing = await manager.query(
          `SELECT id FROM player_inventory WHERE player_id = $1 AND item_type = 'drug' AND LOWER(item_name) = LOWER($2) LIMIT 1`,
          [mission.player_id, mission.drug_name],
        );
        if (existing.length) {
          await manager.query(`UPDATE player_inventory SET quantity = quantity + $1 WHERE id = $2`, [unsold, existing[0].id]);
        } else {
          await manager.query(
            `INSERT INTO player_inventory (player_id, item_type, item_name, quantity, storage_condition) VALUES ($1, 'drug', $2, $3, 'stored')`,
            [mission.player_id, mission.drug_name, unsold],
          );
        }
      }

      // Finalize
      mission.status = 'completed';
      mission.stock_sold = totalSold;
      mission.revenue_total = revenue;
      mission.resolved_at = new Date();
      mission.outcome = {
        incidents_count: totalIncidents,
        arrested_gangsters: arrestedGangsters,
        notes: [`${totalSold}/${mission.stock_reserved} vendus`, `${revenue} ∞ shadow credites`],
      };

      return repo.save(mission);
    });
  }

  // ── CANCEL ──

  static async cancelMission(missionId: string, playerId: string): Promise<DealerMission> {
    return AppDataSource.transaction(async (manager) => {
      const repo = manager.getRepository(DealerMission);
      const mission = await repo.findOneByOrFail({ id: missionId });

      if (mission.player_id !== playerId) throw new Error('Pas votre mission');
      if (mission.status !== 'pending' && mission.status !== 'in_progress') {
        throw new Error(`Impossible d'annuler (status: ${mission.status})`);
      }

      // Return stock
      const existing = await manager.query(
        `SELECT id FROM player_inventory WHERE player_id = $1 AND item_type = 'drug' AND LOWER(item_name) = LOWER($2) LIMIT 1`,
        [playerId, mission.drug_name],
      );
      if (existing.length) {
        await manager.query(`UPDATE player_inventory SET quantity = quantity + $1 WHERE id = $2`, [mission.stock_reserved, existing[0].id]);
      } else {
        await manager.query(
          `INSERT INTO player_inventory (player_id, item_type, item_name, quantity, storage_condition) VALUES ($1, 'drug', $2, $3, 'stored')`,
          [playerId, mission.drug_name, mission.stock_reserved],
        );
      }

      mission.status = 'cancelled';
      return repo.save(mission);
    });
  }

  // ── LIST ──

  static async listPlayerMissions(playerId: string, status?: string): Promise<DealerMission[]> {
    const where: Record<string, unknown> = { player_id: playerId };
    if (status) where.status = status;
    return missionRepo().find({ where: where as any, order: { started_at: 'DESC' }, take: 50 });
  }

  // ── CRON: get missions ready to resolve ──

  static async getResolvableMissions(): Promise<DealerMission[]> {
    return missionRepo().find({
      where: { status: 'in_progress' as const, ends_at: LessThanOrEqual(new Date()) },
    });
  }
}
