/**
 * Phase 8.12 (2026-04-29) — Phone endpoints : appels indic Hugues.
 *
 * Routes :
 *   POST /api/phone/informant/reveal-thief — Révèle le voleur du dernier
 *     vehicle_thefts non révélé pour la victime (le joueur courant).
 *     Gratuit, mais nécessite que le contact 'npc:hugo_indic' soit unlocked
 *     (mission CR_INDIC_HUGUES choix A).
 */
import { Router, Response } from 'express';
import { LessThan } from 'typeorm';
import { requireAuth, AuthRequest } from '../../middleware/auth.middleware';
import { AppDataSource } from '../../config/database';
import { Player } from '../../models/Player';
import { VehicleTheft } from '../../models/VehicleTheft';
import { Vehicle } from '../../models/Vehicle';

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

const HUGUES_CONTACT_CODE = 'npc:hugo_indic';

/**
 * POST /informant/reveal-thief
 * Révèle le voleur du dernier vol non identifié.
 *
 * Réponse 200 :
 *   {
 *     thief_player_id: string,
 *     thief_name: string,
 *     vehicle_id: string,
 *     vehicle_name: string,
 *     occurred_at: string (ISO),
 *     remaining_unrevealed: number  // combien d'autres vols à révéler
 *   }
 *
 * Réponse 404 :
 *   { error: 'Aucun vol à identifier' }
 *
 * Réponse 403 :
 *   { error: 'Contact Hugues non débloqué' }
 */
router.post('/informant/reveal-thief', async (req: AuthRequest, res: Response) => {
  try {
    const playerId = req.playerId!;
    const playerRepo = AppDataSource.getRepository(Player);
    const theftRepo = AppDataSource.getRepository(VehicleTheft);
    const vehicleRepo = AppDataSource.getRepository(Vehicle);

    // Check contact unlocked
    const player = await playerRepo.findOneBy({ id: playerId });
    if (!player) return res.status(404).json({ error: 'Joueur introuvable' });

    const contacts: any[] = Array.isArray(player.contacts) ? player.contacts : [];
    const hasHugues = contacts.some((c) => c?.player_id === HUGUES_CONTACT_CODE);
    if (!hasHugues) {
      return res.status(403).json({ error: 'Contact Hugues non débloqué (mission CR_INDIC_HUGUES requise)' });
    }

    // Last unrevealed theft
    const theft = await theftRepo
      .createQueryBuilder('t')
      .where('t.victim_player_id = :pid', { pid: playerId })
      .andWhere('t.revealed_to_victim_at IS NULL')
      .orderBy('t.occurred_at', 'DESC')
      .getOne();

    if (!theft) {
      return res.status(404).json({ error: 'Aucun vol à identifier' });
    }

    // Set revealed_to_victim_at + method
    await theftRepo.update(
      { id: theft.id },
      { revealed_to_victim_at: new Date(), reveal_method: 'hugues_phone' },
    );

    // Récupère thief_name + vehicle_name pour la réponse
    const [thief, vehicle] = await Promise.all([
      playerRepo.findOneBy({ id: theft.thief_player_id }),
      vehicleRepo.findOneBy({ id: theft.vehicle_id }),
    ]);

    // Compte combien d'autres vols restent à révéler (info UX)
    const remainingCount = await theftRepo
      .createQueryBuilder('t')
      .where('t.victim_player_id = :pid', { pid: playerId })
      .andWhere('t.revealed_to_victim_at IS NULL')
      .getCount();

    res.json({
      thief_player_id: theft.thief_player_id,
      thief_name: thief?.character_name || thief?.username || 'Inconnu',
      vehicle_id: theft.vehicle_id,
      vehicle_name: vehicle?.name || 'Véhicule',
      occurred_at: theft.occurred_at.toISOString(),
      remaining_unrevealed: remainingCount,
    });
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * GET /informant/has-unrevealed
 * Indique si le joueur a au moins un vol non révélé (pour UI gating bouton).
 */
router.get('/informant/has-unrevealed', async (req: AuthRequest, res: Response) => {
  try {
    const playerId = req.playerId!;
    const theftRepo = AppDataSource.getRepository(VehicleTheft);
    const count = await theftRepo
      .createQueryBuilder('t')
      .where('t.victim_player_id = :pid', { pid: playerId })
      .andWhere('t.revealed_to_victim_at IS NULL')
      .getCount();
    res.json({ has_unrevealed: count > 0, count });
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

export default router;
