-- 020 — Planques : POI de type 'hideout' invisibles aux joueurs ennemis
-- Générées automatiquement 1 par km² autour d'un Point de Territoire (cartel ou joueur),
-- avec 200 kg de stockage et 3 emplacements de véhicules cachés.
-- Contenu non volable, survit aux takeovers et saisies police.

CREATE TABLE IF NOT EXISTS hideouts (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  owner_type VARCHAR(10) NOT NULL CHECK (owner_type IN ('player','gang','cartel')),
  owner_id UUID NOT NULL,
  lat DECIMAL(10,7) NOT NULL,
  lng DECIMAL(10,7) NOT NULL,
  name VARCHAR(120),
  -- Capacité de stockage en grammes (200 000 = 200kg)
  storage_capacity_g INT NOT NULL DEFAULT 200000,
  storage_used_g INT NOT NULL DEFAULT 0,
  -- 3 emplacements de véhicules
  vehicle_slots INT NOT NULL DEFAULT 3,
  -- Lien facultatif vers POI / Residence si la planque est rattachée à un bâtiment
  poi_id UUID,
  -- Territoire parent (pour auto-génération)
  parent_territory_type VARCHAR(10), -- 'player' or 'cartel'
  parent_territory_id UUID,
  is_active BOOLEAN NOT NULL DEFAULT true,
  created_at TIMESTAMP NOT NULL DEFAULT NOW(),
  destroyed_at TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_hideouts_owner ON hideouts(owner_type, owner_id, is_active);
CREATE INDEX IF NOT EXISTS idx_hideouts_parent_territory
  ON hideouts(parent_territory_type, parent_territory_id) WHERE is_active = true;

-- Contenu stocké dans une planque (items, armes, drogues)
CREATE TABLE IF NOT EXISTS hideout_stock (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  hideout_id UUID NOT NULL REFERENCES hideouts(id) ON DELETE CASCADE,
  item_type VARCHAR(20) NOT NULL, -- 'weapon', 'armor', 'drug', 'item'
  item_subtype VARCHAR(40),
  quantity INT NOT NULL DEFAULT 1,
  quality INT NOT NULL DEFAULT 50,
  weight_g INT NOT NULL DEFAULT 0,
  deposited_by UUID,
  deposited_at TIMESTAMP NOT NULL DEFAULT NOW(),
  metadata JSONB
);

CREATE INDEX IF NOT EXISTS idx_hideout_stock_hideout ON hideout_stock(hideout_id);

-- Véhicules parkés dans une planque (link vers vehicles)
CREATE TABLE IF NOT EXISTS hideout_vehicles (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  hideout_id UUID NOT NULL REFERENCES hideouts(id) ON DELETE CASCADE,
  vehicle_id UUID NOT NULL,
  parked_by UUID,
  parked_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_hideout_vehicles_hideout ON hideout_vehicles(hideout_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_hideout_vehicles_vehicle ON hideout_vehicles(vehicle_id);

-- Notification handler : ajouter la référence de rupture stockage vers stash
ALTER TABLE residences ADD COLUMN IF NOT EXISTS hideout_id UUID REFERENCES hideouts(id) ON DELETE SET NULL;
