import { Router, Request, Response } from 'express';
import { requireAuth, AuthRequest } from '../../middleware/auth.middleware';
import { AppDataSource } from '../../config/database';
import { RacketZone } from '../../models/RacketZone';
import { Player } from '../../models/Player';
import { Business } from '../../models/Business';
import { GangMember } from '../../models/GangMember';
import { In } from 'typeorm';
import { RacketService } from '../../services/racket.service';

const router = Router();
const zoneRepo = () => AppDataSource.getRepository(RacketZone);
const playerRepo = () => AppDataSource.getRepository(Player);
const businessRepo = () => AppDataSource.getRepository(Business);
const gangMemberRepo = () => AppDataSource.getRepository(GangMember);

/**
 * Phase 16 (2026-04-22) — unification U1 : la logique métier (hull convexe,
 * revenu, collecte CRON, défenseurs, extortion one-shot, extortion team avec
 * option RacketZone) vit dans `RacketService`. Ces routes ne font plus que :
 *   1. résoudre le `playerId` via `requireAuth`
 *   2. valider ownership et cap XP
 *   3. manipuler les tables via TypeORM (CRUD RacketZone/building_ids/gangsters)
 *   4. déléguer les recomputations à `RacketService`
 *
 * L'idéal (Sprint 7) serait d'exposer ces méthodes aussi dans `RacketService`
 * pour un 1:1 route↔service. Pour l'instant on garde la CRUD inline mais
 * toute la géométrie + revenue + collecte est déjà dans le service.
 */

router.use(requireAuth);

router.post('/create', async (req: Request, res: Response) => {
  try {
    const playerId = (req as AuthRequest).playerId!;
    const { building_ids, building_types, cycle_hours, is_recurring, status, assigned_vehicle_id } = req.body;

    const player = await playerRepo().findOne({ where: { id: playerId } });
    if (!player) return res.status(404).json({ error: 'Joueur introuvable' });

    const buildingIds: string[] = Array.isArray(building_ids) ? building_ids.filter(Boolean) : [];
    const buildingTypes: Record<string, 'residence' | 'commerce' | 'usine'> =
      building_types && typeof building_types === 'object' ? building_types : {};

    const maxBuildings = RacketZone.getMaxBuildingsByXP(Number(player.experience) || 0);
    if (buildingIds.length === 0) {
      return res.status(400).json({ error: 'building_ids requis' });
    }
    if (buildingIds.length > maxBuildings) {
      return res.status(400).json({ error: `Trop de bâtiments (max ${maxBuildings})` });
    }

    const safeCycle = Math.max(1, Math.min(168, Number(cycle_hours || 24)));
    const now = new Date();

    const zone = zoneRepo().create({
      player_id: playerId,
      building_ids: buildingIds,
      building_types: buildingTypes,
      assigned_gangster_ids: [],
      assigned_weapons: [],
      assigned_vehicle_id: assigned_vehicle_id || null,
      status: (status && ['active', 'paused', 'contested', 'broken'].includes(status)) ? status : 'active',
      cycle_hours: safeCycle,
      is_recurring: typeof is_recurring === 'boolean' ? is_recurring : true,
      last_collection: null,
      next_collection: new Date(now.getTime() + safeCycle * 60 * 60 * 1000),
      convex_hull: [],
      center_lat: null,
      center_lon: null,
      max_buildings: maxBuildings,
    });
    zone.calculateRevenue();
    const saved = await zoneRepo().save(zone);

    // Recompute geometry via RacketService (source unique — hull convex)
    const refreshed = await RacketService.recomputeZoneGeometry(saved.id);
    res.status(201).json(refreshed ?? saved);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.get('/mine', async (req: Request, res: Response) => {
  try {
    const playerId = (req as AuthRequest).playerId!;
    const zones = await zoneRepo().find({ where: { player_id: playerId }, order: { created_at: 'DESC' } });
    res.json(zones);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.put('/:id', async (req: Request, res: Response) => {
  try {
    const playerId = (req as AuthRequest).playerId!;
    const zone = await zoneRepo().findOne({ where: { id: req.params.id, player_id: playerId } });
    if (!zone) return res.status(404).json({ error: 'Zone introuvable' });

    const player = await playerRepo().findOne({ where: { id: playerId } });
    if (!player) return res.status(404).json({ error: 'Joueur introuvable' });

    const { building_ids, building_types, cycle_hours, is_recurring, status, assigned_vehicle_id } = req.body;

    const buildingIds: string[] = Array.isArray(building_ids) ? building_ids.filter(Boolean) : zone.building_ids;
    const buildingTypes: Record<string, 'residence' | 'commerce' | 'usine'> =
      building_types && typeof building_types === 'object' ? building_types : zone.building_types;

    const maxBuildings = RacketZone.getMaxBuildingsByXP(Number(player.experience) || 0);
    if (buildingIds.length === 0) {
      return res.status(400).json({ error: 'building_ids requis' });
    }
    if (buildingIds.length > maxBuildings) {
      return res.status(400).json({ error: `Trop de bâtiments (max ${maxBuildings})` });
    }

    const safeCycle = cycle_hours != null ? Math.max(1, Math.min(168, Number(cycle_hours || 24))) : zone.cycle_hours;

    zone.building_ids = buildingIds;
    zone.building_types = buildingTypes;
    zone.max_buildings = maxBuildings;
    zone.cycle_hours = safeCycle;
    if (typeof is_recurring === 'boolean') zone.is_recurring = is_recurring;
    if (assigned_vehicle_id !== undefined) zone.assigned_vehicle_id = assigned_vehicle_id || null;
    if (status && ['active', 'paused', 'contested', 'broken'].includes(status)) zone.status = status;

    zone.calculateRevenue();
    await zoneRepo().save(zone);

    // Recompute geometry via RacketService (source unique)
    const refreshed = await RacketService.recomputeZoneGeometry(zone.id);
    res.json(refreshed ?? zone);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

/**
 * Phase 8 v3 (2026-05-02) — "Tout le monde à sa part" toggle.
 * PATCH /api/racket/zone/:id/share-to-police { enabled: boolean }
 *
 * Switch le flag share_to_police de la zone (10% revenu au commissariat
 * local en échange d'inhibition heat racket). Ownership check :
 * seul player_id de la zone peut toggle. Effet immédiat à la prochaine
 * collecte cron (toutes les zone.cycle_hours, par défaut 24h).
 */
router.patch('/:id/share-to-police', async (req: Request, res: Response) => {
  try {
    const playerId = (req as AuthRequest).playerId!;
    const enabled = req.body?.enabled;
    if (typeof enabled !== 'boolean') {
      return res.status(400).json({ error: 'enabled (boolean) requis' });
    }
    const zone = await zoneRepo().findOne({ where: { id: req.params.id, player_id: playerId } });
    if (!zone) return res.status(404).json({ error: 'Zone introuvable ou non possédée' });

    zone.share_to_police = enabled;
    await zoneRepo().save(zone);

    res.json({
      id: zone.id,
      share_to_police: zone.share_to_police,
      status: zone.status,
      effective: enabled && zone.status === 'active',
      message: enabled
        ? (zone.status === 'active'
            ? 'Bribe police activé (10% revenu reversé, chaleur inhibée). Effectif à la prochaine collecte.'
            : `Bribe police mémorisé. Inactif tant que la zone n'est pas en status='active' (actuellement '${zone.status}').`)
        : '"Ne rien lâcher" — bribe police désactivé. La chaleur racket reprend à la prochaine collecte.',
    });
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.delete('/:id', async (req: Request, res: Response) => {
  try {
    const playerId = (req as AuthRequest).playerId!;
    const zone = await zoneRepo().findOne({ where: { id: req.params.id, player_id: playerId } });
    if (!zone) return res.status(404).json({ error: 'Zone introuvable' });

    const membership = await gangMemberRepo().findOne({ where: { player_id: playerId } });
    const gangId = membership?.gang_id ?? null;

    if (gangId && zone.assigned_gangster_ids?.length) {
      await gangMemberRepo().update(
        { gang_id: gangId, player_id: In(zone.assigned_gangster_ids) },
        { assigned_racket_zone_id: null },
      );
    }

    // Détacher aussi les businesses pointant sur cette zone
    if (Array.isArray(zone.building_ids) && zone.building_ids.length > 0) {
      await businessRepo().update(
        { id: In(zone.building_ids), racket_zone_id: zone.id } as any,
        { racket_zone_id: null } as any,
      );
    }

    await zoneRepo().delete(zone.id);
    res.json({ success: true });
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.post('/:id/assign-gangster', async (req: Request, res: Response) => {
  try {
    const playerId = (req as AuthRequest).playerId!;
    const zone = await zoneRepo().findOne({ where: { id: req.params.id, player_id: playerId } });
    if (!zone) return res.status(404).json({ error: 'Zone introuvable' });

    const { gangster_ids } = req.body;
    const gangsterIds: string[] = Array.isArray(gangster_ids) ? gangster_ids.filter(Boolean) : [];

    const membership = await gangMemberRepo().findOne({ where: { player_id: playerId } });
    const gangId = membership?.gang_id ?? null;
    if (!gangId) return res.status(400).json({ error: 'Aucun gang' });

    const candidates = gangsterIds.length
      ? await gangMemberRepo().find({ where: { gang_id: gangId, player_id: In(gangsterIds) } })
      : [];

    if (candidates.length !== gangsterIds.length) {
      return res.status(400).json({ error: 'Gangster invalide' });
    }
    for (const g of candidates) {
      if (!g.isAvailable && g.assigned_racket_zone_id !== zone.id) {
        return res.status(400).json({ error: 'Un gangster est indisponible' });
      }
    }

    const previous = Array.isArray(zone.assigned_gangster_ids) ? zone.assigned_gangster_ids : [];
    const prevToClear = previous.filter((id) => !gangsterIds.includes(id));
    const toAssign = gangsterIds;

    if (prevToClear.length) {
      await gangMemberRepo().update(
        { gang_id: gangId, player_id: In(prevToClear), assigned_racket_zone_id: zone.id },
        { assigned_racket_zone_id: null },
      );
    }
    if (toAssign.length) {
      await gangMemberRepo().update(
        { gang_id: gangId, player_id: In(toAssign) },
        { assigned_racket_zone_id: zone.id },
      );
    }

    zone.assigned_gangster_ids = toAssign;
    zone.calculateRevenue();
    await zoneRepo().save(zone);
    res.json(zone);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.post('/:id/assign-weapon', async (req: Request, res: Response) => {
  try {
    const playerId = (req as AuthRequest).playerId!;
    const zone = await zoneRepo().findOne({ where: { id: req.params.id, player_id: playerId } });
    if (!zone) return res.status(404).json({ error: 'Zone introuvable' });

    const { gangster_id, weapon } = req.body;
    if (!gangster_id || !weapon) return res.status(400).json({ error: 'gangster_id et weapon requis' });

    const membership = await gangMemberRepo().findOne({ where: { player_id: playerId } });
    const gangId = membership?.gang_id ?? null;
    if (!gangId) return res.status(400).json({ error: 'Aucun gang' });

    if (!Array.isArray(zone.assigned_gangster_ids) || !zone.assigned_gangster_ids.includes(gangster_id)) {
      return res.status(400).json({ error: 'Gangster non assigné à la zone' });
    }

    const gm = await gangMemberRepo().findOne({ where: { gang_id: gangId, player_id: gangster_id } });
    if (!gm) return res.status(404).json({ error: 'Gangster introuvable' });

    await gangMemberRepo().update({ gang_id: gangId, player_id: gangster_id }, { assigned_weapon: String(weapon) });
    const weapons = Array.isArray(zone.assigned_weapons) ? zone.assigned_weapons : [];
    if (!weapons.includes(String(weapon))) weapons.push(String(weapon));
    zone.assigned_weapons = weapons;
    await zoneRepo().save(zone);

    res.json({ success: true });
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

export default router;
