-- ============================================================
-- Migration 067 (Phase 8.12, 2026-04-29) — Audit table vehicle_thefts
-- ============================================================
-- Permet à Hugues (mission CR_INDIC_HUGUES) de révéler le nom du voleur
-- du dernier vol non identifié.
--
-- Spec user :
--   - Quand un véhicule est volé, on insère une row dans vehicle_thefts
--     avec revealed_to_victim_at = NULL si le voleur reste anonyme
--     (4 conditions reveal : message échangé / cartel commun / chaleur≥90
--     / indic actif).
--   - Quand le voleur N'est PAS anonyme → revealed_to_victim_at = now
--     (déjà connu, pas besoin de Hugues pour révéler).
--   - Hugues : SELECT WHERE victim=me AND revealed_to_victim_at IS NULL
--     ORDER BY occurred_at DESC LIMIT 1 → reveal next.
--
-- Idempotente : CREATE TABLE IF NOT EXISTS, CREATE INDEX IF NOT EXISTS.
-- ============================================================

CREATE TABLE IF NOT EXISTS vehicle_thefts (
  id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
  vehicle_id uuid NOT NULL,
  victim_player_id uuid NOT NULL,
  thief_player_id uuid NOT NULL,
  occurred_at timestamp NOT NULL DEFAULT NOW(),
  revealed_to_victim_at timestamp,
  reveal_method varchar(30),
  CONSTRAINT fk_vehicle_thefts_vehicle FOREIGN KEY (vehicle_id) REFERENCES vehicles(id) ON DELETE CASCADE,
  CONSTRAINT fk_vehicle_thefts_victim FOREIGN KEY (victim_player_id) REFERENCES players(id) ON DELETE CASCADE,
  CONSTRAINT fk_vehicle_thefts_thief FOREIGN KEY (thief_player_id) REFERENCES players(id) ON DELETE CASCADE
);

-- Index pour Hugues lookup : "dernier vol non révélé pour ce victim"
CREATE INDEX IF NOT EXISTS idx_vehicle_thefts_unrevealed
  ON vehicle_thefts(victim_player_id, occurred_at DESC)
  WHERE revealed_to_victim_at IS NULL;

-- Index pour audit/historique
CREATE INDEX IF NOT EXISTS idx_vehicle_thefts_thief
  ON vehicle_thefts(thief_player_id);

-- ============================================================
-- Contrôle post-migration (decommenter pour debug)
-- ============================================================
-- SELECT column_name FROM information_schema.columns WHERE table_name='vehicle_thefts';
