import { Router, Response } from 'express';
import { requireAuth, AuthRequest } from '../../middleware/auth.middleware';
import { AppDataSource } from '../../config/database';
import { GangService } from '../../services/gang.service';
import { GangOrderService } from '../../services/gang-order.service';

const router = Router();
router.use(requireAuth);

// ==========================================
// CRUD GANG
// ==========================================

/** POST /gang/create — Créer un gang */
router.post('/create', async (req: AuthRequest, res: Response) => {
  try {
    const gang = await GangService.createGang(req.playerId!, req.body);
    res.json(gang);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** GET /gang/mine — Mon gang actuel (avec détails complets) */
router.get('/mine', async (req: AuthRequest, res: Response) => {
  try {
    const gang = await GangService.getPlayerGang(req.playerId!);
    if (!gang) return res.json(null);
    res.json(gang);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** GET /gang/list — Lister tous les gangs */
router.get('/list', async (req: AuthRequest, res: Response) => {
  try {
    const gangs = await GangService.listGangs({
      is_npc: req.query.npc === 'true' ? true : req.query.npc === 'false' ? false : undefined,
      zone_id: req.query.zone_id as string | undefined,
    });
    res.json(gangs);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** GET /gang/:id — Détails d'un gang */
router.get('/:id', async (req: AuthRequest, res: Response) => {
  try {
    const gang = await GangService.getGangFull(req.params.id);
    res.json(gang);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

router.post('/:id/request-join', async (req: AuthRequest, res: Response) => {
  try {
    const result = await GangService.requestJoin(req.params.id, req.playerId!);
    res.json(result);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

// ==========================================
// MEMBRES
// ==========================================

/** POST /gang/:id/invite — Inviter un joueur */
router.post('/:id/invite', async (req: AuthRequest, res: Response) => {
  try {
    await GangService.inviteMember(req.params.id, req.playerId!, req.body.player_id);
    res.json({ success: true });
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** POST /gang/:id/remove — Retirer un membre */
router.post('/:id/remove', async (req: AuthRequest, res: Response) => {
  try {
    await GangService.removeMember(req.params.id, req.playerId!, req.body.player_id);
    res.json({ success: true });
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** POST /gang/:id/leave — Quitter le gang */
router.post('/:id/leave', async (req: AuthRequest, res: Response) => {
  try {
    await GangService.removeMember(req.params.id, req.playerId!, req.playerId!);
    res.json({ success: true });
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** POST /gang/:id/promote — Promouvoir un membre */
router.post('/:id/promote', async (req: AuthRequest, res: Response) => {
  try {
    await GangService.promoteMember(req.params.id, req.playerId!, req.body.player_id, req.body.role);
    res.json({ success: true });
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** POST /gang/:id/fire-bras-droit — Phase 8a (2026-04-26) Licencier le bras droit */
router.post('/:id/fire-bras-droit', async (req: AuthRequest, res: Response) => {
  try {
    const result = await GangService.fireBrasDroit(req.params.id, req.playerId!);
    res.json({ success: true, ...result });
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

// ==========================================
// ASSETS (Entrepôts, Véhicules, Businesses, Résidences)
// ==========================================

/** POST /gang/:id/asset — Assigner un bien au gang */
router.post('/:id/asset', async (req: AuthRequest, res: Response) => {
  try {
    const asset = await GangService.assignAsset(req.params.id, req.playerId!, req.body);
    res.json(asset);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** DELETE /gang/:id/asset/:assetId — Retirer un bien */
router.delete('/:id/asset/:assetId', async (req: AuthRequest, res: Response) => {
  try {
    await GangService.removeAsset(req.params.id, req.playerId!, req.params.assetId);
    res.json({ success: true });
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

// ==========================================
// COFFRE (Stock + Trésorerie)
// ==========================================

/** POST /gang/:id/deposit-item — Déposer un item dans le coffre */
router.post('/:id/deposit-item', async (req: AuthRequest, res: Response) => {
  try {
    const item = await GangService.depositItem(
      req.params.id, req.playerId!, req.body.inventory_id, req.body.quantity,
    );
    res.json(item);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** POST /gang/:id/withdraw-item — Retirer un item du coffre */
router.post('/:id/withdraw-item', async (req: AuthRequest, res: Response) => {
  try {
    const item = await GangService.withdrawItem(
      req.params.id, req.playerId!, req.body.stock_id, req.body.quantity,
    );
    res.json(item);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** POST /gang/:id/deposit-money — Déposer de l'argent */
router.post('/:id/deposit-money', async (req: AuthRequest, res: Response) => {
  try {
    await GangService.depositMoney(
      req.params.id, req.playerId!, req.body.currency_type, req.body.amount,
    );
    res.json({ success: true });
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** POST /gang/:id/withdraw-money — Retirer de l'argent */
router.post('/:id/withdraw-money', async (req: AuthRequest, res: Response) => {
  try {
    await GangService.withdrawMoney(
      req.params.id, req.playerId!, req.body.currency_type, req.body.amount,
    );
    res.json({ success: true });
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

// ==========================================
// DEMANDES DE RESSOURCES + VOTES
// ==========================================

/** POST /gang/:id/request — Demander une ressource */
router.post('/:id/request', async (req: AuthRequest, res: Response) => {
  try {
    const request = await GangService.createResourceRequest(req.params.id, req.playerId!, req.body);
    res.json(request);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** GET /gang/:id/requests — Lister les demandes */
router.get('/:id/requests', async (req: AuthRequest, res: Response) => {
  try {
    const requests = await GangService.getRequests(
      req.params.id, req.query.status as any,
    );
    res.json(requests);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** POST /gang/:id/request/:reqId/review — Approuver/Rejeter (hiérarchique) ou voter (coopératif) */
router.post('/:id/request/:reqId/review', async (req: AuthRequest, res: Response) => {
  try {
    const result = await GangService.reviewRequest(
      req.params.id, req.playerId!, req.params.reqId,
      req.body.approve, req.body.note,
    );
    res.json(result);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** POST /gang/:id/request/:reqId/vote — Vote (mode coopératif) */
router.post('/:id/request/:reqId/vote', async (req: AuthRequest, res: Response) => {
  try {
    const result = await GangService.voteOnRequest(
      req.params.id, req.playerId!, req.params.reqId, req.body.vote,
    );
    res.json(result);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

// ==========================================
// ORDRES GANGSTER (audit 15-04-2026, Phase 4)
// Routes HTTP autour de GangOrderService. Wrappe le systeme Journey
// existant avec des metadonnees d'ordre (order_type, target_id, etc.).
// ==========================================

/**
 * POST /gang/:id/order/create
 * Body: {
 *   member_player_id: string;     // gangster cible
 *   order_type: 'mission' | 'patrol' | 'guard' | 'racket' | 'collect' | 'escort' | 'recon' | 'dead_drop';
 *   destination: { lat: number; lon: number };
 *   target_type?: string;          // business, residence, poi, player, racket_zone
 *   target_id?: string;            // uuid de la cible
 *   order_params?: object;         // params libres selon order_type
 *   vehicle_id?: string;
 *   mission_progress_id?: string;  // si order_type='mission'
 * }
 */
router.post('/:id/order/create', async (req: AuthRequest, res: Response) => {
  try {
    const body = req.body || {};
    if (!body.member_player_id || !body.order_type || !body.destination) {
      return res.status(400).json({ error: 'member_player_id, order_type, destination requis' });
    }
    if (typeof body.destination.lat !== 'number' || typeof body.destination.lon !== 'number') {
      return res.status(400).json({ error: 'destination.lat/lon invalides' });
    }

    const journey = await GangOrderService.createOrder({
      gangId: req.params.id,
      memberPlayerId: body.member_player_id,
      orderType: body.order_type,
      destination: body.destination,
      targetType: body.target_type || null,
      targetId: body.target_id || null,
      orderParams: body.order_params || {},
      vehicleId: body.vehicle_id,
      requestedBy: req.playerId!,
      missionProgressId: body.mission_progress_id,
    });
    res.status(201).json(journey);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** GET /gang/:id/orders — Liste des ordres actifs (in_transit, non travel) */
router.get('/:id/orders', async (req: AuthRequest, res: Response) => {
  try {
    const orders = await GangOrderService.listActiveOrders(req.params.id);
    res.json(orders);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** GET /gang/:id/orders/recent — Liste des ordres recemment termines (avec outcome) */
router.get('/:id/orders/recent', async (req: AuthRequest, res: Response) => {
  try {
    const limit = Math.min(100, Math.max(1, parseInt(req.query.limit as string) || 10));
    const orders = await GangOrderService.listRecentOutcomes(req.params.id, limit);
    res.json(orders);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** POST /gang/order/:journeyId/cancel — Annule un ordre en cours */
router.post('/order/:journeyId/cancel', async (req: AuthRequest, res: Response) => {
  try {
    await GangOrderService.cancelOrder(req.params.journeyId, req.playerId!);
    res.json({ success: true });
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

// ═══════════════════════════════════════════════════════════════
// audit 15-04-2026 Phase 13.d — NPC Recruit Pool routes
// ═══════════════════════════════════════════════════════════════

/**
 * Phase 17 fix (2026-05-04) — GET /gang/:id/drug-stocks
 * Retourne les drogues présentes dans le coffre du gang (gang_stock),
 * agrégées par item_subtype. Utilisé par DealerMissionCreateModal.
 *
 * Bug fixé : l'ancien endpoint /api/player/inventory?type=drug n'existe
 * pas (la vraie route est /api/player/:id/inventory) ET la mission
 * dealer est de scope gang donc il faut lire le gang_stock, pas le
 * player.inventory.
 */
router.get('/:id/drug-stocks', async (req: AuthRequest, res: Response) => {
  try {
    const { GangStock } = await import('../../models/GangStock');
    const rows = await AppDataSource.getRepository(GangStock)
      .createQueryBuilder('s')
      .select('s.item_subtype', 'item_subtype')
      .addSelect('SUM(s.quantity)::int', 'quantity')
      .where('s.gang_id = :gid', { gid: req.params.id })
      .andWhere("s.item_type = 'drug'")
      .groupBy('s.item_subtype')
      .having('SUM(s.quantity) > 0')
      .getRawMany();
    res.json(rows.map((r: any) => ({
      item_name: r.item_subtype,
      quantity: Number(r.quantity) || 0,
    })));
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/**
 * GET /gang/recruit-pool — Pool de recrues NPC du joueur.
 *
 * Phase 17 (2026-05-04) — Fallback stale-pool : si le cron a sauté un
 * minuit (downtime PM2 / deploy raté), on force un refresh à la lecture
 * dès lors que `refreshed_at` est antérieur à minuit Paris du jour
 * courant. Combiné au catch-up boot du nouveau scheduleDailyAtParisHour,
 * le joueur a la garantie de toujours voir un pool à jour.
 */
router.get('/recruit-pool', async (req: AuthRequest, res: Response) => {
  try {
    const { NpcRecruitService } = await import('../../services/npc-recruit.service');
    let pool = await NpcRecruitService.getPool(req.playerId!);

    // Stale check : pool plus ancien que minuit Paris du jour courant.
    // `Intl.DateTimeFormat` gère le DST (CET/CEST) automatiquement,
    // donc on compare juste les YYYY-MM-DD Paris.
    const fmt = new Intl.DateTimeFormat('en-CA', {
      timeZone: 'Europe/Paris',
      year: 'numeric', month: '2-digit', day: '2-digit',
    });
    const todayParis = fmt.format(new Date());
    const refreshedDay = pool?.refreshed_at ? fmt.format(pool.refreshed_at) : null;

    if (!pool || refreshedDay !== todayParis) {
      pool = await NpcRecruitService.refreshPoolForPlayer(req.playerId!);
    }

    res.json({
      size: pool.size,
      has_elite: pool.has_elite,
      slots: pool.slots.filter(s => !s.recruited),
      refreshed_at: pool.refreshed_at,
      next_refresh_at: pool.next_refresh_at,
    });
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/**
 * POST /gang/recruit-from-pool/:slotId — Recrute un candidat du pool.
 */
router.post('/recruit-from-pool/:slotId', async (req: AuthRequest, res: Response) => {
  try {
    const { NpcRecruitService } = await import('../../services/npc-recruit.service');
    const result = await NpcRecruitService.recruitFromPool(req.playerId!, req.params.slotId);
    res.json(result);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/**
 * POST /gang/dismiss-from-pool/:slotId — Sortir un candidat du pool (Phase 15).
 */
router.post('/dismiss-from-pool/:slotId', async (req: AuthRequest, res: Response) => {
  try {
    const { NpcRecruitService } = await import('../../services/npc-recruit.service');
    const result = await NpcRecruitService.dismissCandidate(req.playerId!, req.params.slotId);
    res.json(result);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/**
 * POST /gang/:id/member/:playerId/pay-now — Payer un arriéré de salaire (Phase 15).
 */
router.post('/:id/member/:playerId/pay-now', async (req: AuthRequest, res: Response) => {
  try {
    const { GangPayrollService } = await import('../../services/gang-payroll.service');
    const result = await GangPayrollService.payNow(req.params.id, req.params.playerId);
    res.json(result);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

export default router;

