import { Router, Response } from 'express';
import { requireAuth, AuthRequest } from '../../middleware/auth.middleware';
import { SpecialistService } from '../../services/specialist.service';

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

/** GET /specialists/pool/:role — Liste les specialists NPC dispo (bassin) */
router.get('/pool/:role', async (req: AuthRequest, res: Response) => {
  try {
    const role = req.params.role as 'lawyer' | 'accountant' | 'informant';
    if (!['lawyer', 'accountant', 'informant'].includes(role)) {
      return res.status(400).json({ error: 'Role invalide' });
    }
    res.json(await SpecialistService.listNpcPool(role));
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** GET /specialists/mine — Mes specialists (portée player) */
router.get('/mine', async (req: AuthRequest, res: Response) => {
  try { res.json(await SpecialistService.listForOwner('player', req.playerId!)); }
  catch (err: any) { res.status(400).json({ error: err.message }); }
});

/**
 * POST /specialists/hire — Rattacher un specialist au joueur/gang/cartel.
 *
 * Phase 17 (2026-05-04) — Body accepte optionnellement `daily_rate` pour
 * négocier le tarif/jour dans la fourchette autorisée par le rôle :
 *   • lawyer/accountant/informant : prix fixe (ignoré si fourni)
 *   • detective : ∈ [10 × skill, 20 × skill]
 *   • medic     : ∈ [80, 140]
 * Si non fourni : tarif médian par défaut (rétrocompat).
 */
router.post('/hire', async (req: AuthRequest, res: Response) => {
  try {
    const { specialist_id, owner_type = 'player', owner_id, daily_rate } = req.body || {};
    const effectiveOwnerId = owner_type === 'player' ? req.playerId! : owner_id;
    if (!specialist_id || !effectiveOwnerId) {
      return res.status(400).json({ error: 'specialist_id et owner_id requis' });
    }
    const chosenRate = typeof daily_rate === 'number' && Number.isFinite(daily_rate)
      ? Math.round(daily_rate)
      : undefined;
    const att = await SpecialistService.hire(owner_type, effectiveOwnerId, specialist_id, chosenRate);
    res.json(att);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** POST /specialists/:attId/fire */
router.post('/:attId/fire', async (req: AuthRequest, res: Response) => {
  try {
    await SpecialistService.fire(req.params.attId);
    res.json({ success: true });
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** GET /specialists/owner/:ownerType/:ownerId */
router.get('/owner/:ownerType/:ownerId', async (req: AuthRequest, res: Response) => {
  try {
    const t = req.params.ownerType as any;
    if (!['player', 'gang', 'cartel'].includes(t)) return res.status(400).json({ error: 'owner_type invalide' });
    res.json(await SpecialistService.listForOwner(t, req.params.ownerId));
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/**
 * Phase 17 (2026-05-04) — GET /specialists/detective/reveals
 * Liste les POI revelations actives (TTL 7j) pour le player connecté
 * (scope='player'). Frontend les affiche sur la carte avec un badge
 * "Enquêteur" + lightbox détaillée au clic.
 *
 * Query optionnel : ?scope=player|gang|cartel&owner_id=...
 * Default : player du token.
 */
router.get('/detective/reveals', async (req: AuthRequest, res: Response) => {
  try {
    const { DetectiveService } = await import('../../services/detective.service');
    const scope = (req.query.scope as 'player' | 'gang' | 'cartel') || 'player';
    const ownerId = (req.query.owner_id as string) || req.playerId!;
    const enriched = req.query.enriched === 'true' || req.query.enriched === '1';
    if (!['player', 'gang', 'cartel'].includes(scope)) {
      return res.status(400).json({ error: 'scope invalide' });
    }
    const reveals = enriched
      ? await DetectiveService.listActiveRevelationsEnriched(scope, ownerId)
      : await DetectiveService.listActiveRevelations(scope, ownerId);
    res.json(reveals);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/**
 * Phase 17 (2026-05-04) — POST /specialists/medic/call
 * Appel on-call du médecin perso. Body :
 *   { points: number,                    // 1..PV manquants
 *     currency: 'shadow' | 'light' }     // au choix joueur
 * Coût : 100 ∞ × points dans la devise choisie.
 * Livraison : 1 PV/min via PlayerHealth.healing_pts_remaining.
 */
router.post('/medic/call', async (req: AuthRequest, res: Response) => {
  try {
    const { MedicService } = await import('../../services/medic.service');
    const points = Number(req.body?.points ?? 0);
    const currency = (req.body?.currency === 'light' ? 'light' : 'shadow') as 'shadow' | 'light';
    if (!Number.isFinite(points) || points <= 0) {
      return res.status(400).json({ error: 'points doit être un entier > 0' });
    }
    const result = await MedicService.callOnDemand(req.playerId!, points, currency);
    res.json(result);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

export default router;
