-- ============================================================
-- Migration 068 (Phase 8.11b, 2026-04-29) — Slots de parking auto
-- ============================================================
-- Spec user : pour chaque territoire joueur, on génère des slots invisibles
-- de parking le long des rues environnantes (rayon 100m via Overpass API),
-- tous les ~4m alternance gauche/droite. Au moment de l'achat ou du vol
-- d'un véhicule, on l'assigne au premier slot libre (du plus proche au
-- plus loin du territoire). Les véhicules apparaissent à leurs positions
-- de slot sur la map (les slots eux-mêmes sont invisibles).
--
-- Format slots :
--   - lat/lon = position GPS calculée perpendiculairement au segment routier
--   - slot_index = ordre de proximité au territoire (0 = plus proche)
--   - vehicle_id = NULL si libre, UUID du véhicule sinon
--   - osm_way_id = identifiant Overpass de la rue d'origine (audit)
--   - side = 'left' | 'right' (côté de la rue)
--
-- Idempotente : CREATE TABLE IF NOT EXISTS, CREATE INDEX IF NOT EXISTS.
-- ============================================================

CREATE TABLE IF NOT EXISTS vehicle_parking_slots (
  id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
  owner_player_id uuid NOT NULL,
  slot_index int NOT NULL,
  lat decimal(10, 8) NOT NULL,
  lon decimal(11, 8) NOT NULL,
  vehicle_id uuid,
  osm_way_id bigint,
  side varchar(5),
  generated_at timestamp NOT NULL DEFAULT NOW(),
  CONSTRAINT fk_parking_slots_owner FOREIGN KEY (owner_player_id) REFERENCES players(id) ON DELETE CASCADE,
  CONSTRAINT fk_parking_slots_vehicle FOREIGN KEY (vehicle_id) REFERENCES vehicles(id) ON DELETE SET NULL
);

-- Index : "premier slot libre du joueur ordonné par distance territoire"
CREATE INDEX IF NOT EXISTS idx_parking_slots_owner_index
  ON vehicle_parking_slots(owner_player_id, slot_index)
  WHERE vehicle_id IS NULL;

-- Index : "slot occupé par un véhicule donné" (pour libération au vol/vente)
CREATE INDEX IF NOT EXISTS idx_parking_slots_vehicle
  ON vehicle_parking_slots(vehicle_id) WHERE vehicle_id IS NOT NULL;

-- Index unique : 1 véhicule = 1 slot max (garde-fou intégrité)
CREATE UNIQUE INDEX IF NOT EXISTS uniq_parking_slots_vehicle
  ON vehicle_parking_slots(vehicle_id) WHERE vehicle_id IS NOT NULL;

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