-- Colonnes utilisées par l'API et le geocoder mais absentes du schéma initial
ALTER TABLE bands ADD COLUMN IF NOT EXISTS enriched         BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE bands ADD COLUMN IF NOT EXISTS themes           TEXT;
ALTER TABLE bands ADD COLUMN IF NOT EXISTS geocoded_at      TIMESTAMPTZ;
ALTER TABLE bands ADD COLUMN IF NOT EXISTS geocode_provider TEXT;
ALTER TABLE bands ADD COLUMN IF NOT EXISTS geocode_query    TEXT;
ALTER TABLE bands ADD COLUMN IF NOT EXISTS geocode_raw      JSONB;
ALTER TABLE bands ADD COLUMN IF NOT EXISTS geocode_error    TEXT;
ALTER TABLE bands ADD COLUMN IF NOT EXISTS geocode_error_at TIMESTAMPTZ;

-- Fix: le trigger précédent ne mettait updated_at à jour que sur changement de lat/lon.
-- Le remplacer pour qu'il se déclenche sur n'importe quelle UPDATE.
CREATE OR REPLACE FUNCTION bands_set_geom() RETURNS trigger AS $$
BEGIN
  -- Ne recalculer geom que si lat ou lon a vraiment changé
  IF TG_OP = 'INSERT'
     OR OLD.lat IS DISTINCT FROM NEW.lat
     OR OLD.lon IS DISTINCT FROM NEW.lon
  THEN
    IF NEW.lat IS NOT NULL AND NEW.lon IS NOT NULL THEN
      NEW.geom := ST_SetSRID(ST_MakePoint(NEW.lon, NEW.lat), 4326)::geography;
    ELSE
      NEW.geom := NULL;
    END IF;
  END IF;
  NEW.updated_at := now();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trg_bands_set_geom ON bands;
CREATE TRIGGER trg_bands_set_geom
BEFORE INSERT OR UPDATE ON bands
FOR EACH ROW EXECUTE FUNCTION bands_set_geom();

CREATE INDEX IF NOT EXISTS idx_bands_enriched   ON bands (enriched);
CREATE INDEX IF NOT EXISTS idx_bands_geocoded_at ON bands (geocoded_at);
