-- ============================================================
--  Tablas del dominio — Sistema de Recolección Inteligente
--  Ejecutar ANTES que rls_policies.sql
--  Supabase > SQL Editor
-- ============================================================

-- ------------------------------------------------------------
-- 1. UNITS  (camiones recolectores)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS public.units (
    id     INT PRIMARY KEY,        -- truckId del JSON (101, 103, …)
    plate  TEXT,
    status TEXT DEFAULT 'active'
           CHECK (status IN ('active', 'inactive', 'maintenance'))
);

-- ------------------------------------------------------------
-- 2. ROUTES  (6 rutas MVP)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS public.routes (
    id                  TEXT PRIMARY KEY,   -- 'RUTA-01' … 'RUTA-13'
    name                TEXT,
    truck_id            INT REFERENCES public.units(id),
    turno               TEXT CHECK (turno IN ('matutino', 'vespertino', 'Matutino', 'Vespertino')),
    status              TEXT DEFAULT 'pendiente'
                            CHECK (status IN ('pendiente','en_ruta','completada','diferida','reasignada')),
    current_position_id INT  DEFAULT 1 CHECK (current_position_id BETWEEN 1 AND 8)
);

-- ------------------------------------------------------------
-- 3. ROUTE_POSITIONS  (8 posiciones por ruta — solo admin)
--    ⚠️ Contiene lat/lng. NUNCA se devuelve al ciudadano.
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS public.route_positions (
    route_id    TEXT REFERENCES public.routes(id) ON DELETE CASCADE,
    position_id INT,
    lat         DOUBLE PRECISION,
    lng         DOUBLE PRECISION,
    speed       INT,
    ts          TIMESTAMPTZ,
    PRIMARY KEY (route_id, position_id)
);

-- ------------------------------------------------------------
-- 4. COLONIAS  (mapeo colonia → ruta; sin coordenadas)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS public.colonias (
    id               SERIAL PRIMARY KEY,
    nombre           TEXT NOT NULL,
    route_id         TEXT REFERENCES public.routes(id),
    turno            TEXT,
    horario_estimado TEXT
);

-- ------------------------------------------------------------
-- 5. DRIVERS  (chofer → unidad; 1:1)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS public.drivers (
    id      UUID DEFAULT gen_random_uuid() PRIMARY KEY,
    user_id UUID REFERENCES public.users(id) ON DELETE CASCADE,
    unit_id INT  REFERENCES public.units(id)
);

-- ------------------------------------------------------------
-- 6. COLLECTION_EVENTS  (registro de recolección por domicilio)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS public.collection_events (
    id           UUID DEFAULT gen_random_uuid() PRIMARY KEY,
    route_id     TEXT REFERENCES public.routes(id),
    address_id   UUID REFERENCES public.addresses(id) ON DELETE CASCADE,
    status       TEXT,
    collected_at TIMESTAMPTZ DEFAULT NOW()
);

-- ------------------------------------------------------------
-- 7. ROUTE_CHANGES  (historial de reasignaciones / retrasos)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS public.route_changes (
    id         UUID DEFAULT gen_random_uuid() PRIMARY KEY,
    route_id   TEXT REFERENCES public.routes(id),
    from_unit  INT  REFERENCES public.units(id),
    to_unit    INT  REFERENCES public.units(id),
    reason     TEXT,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

-- ------------------------------------------------------------
-- Índices de rendimiento
-- ------------------------------------------------------------
CREATE INDEX IF NOT EXISTS idx_route_positions_route ON public.route_positions(route_id);
CREATE INDEX IF NOT EXISTS idx_colonias_route        ON public.colonias(route_id);
CREATE INDEX IF NOT EXISTS idx_drivers_user          ON public.drivers(user_id);
CREATE INDEX IF NOT EXISTS idx_collection_route      ON public.collection_events(route_id);

-- ------------------------------------------------------------
-- 8. INCIDENTS  (reportes de ciudadanos sobre unidades)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS public.incidents (
    id          BIGSERIAL PRIMARY KEY,
    user_id     UUID NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
    unit_id     INT REFERENCES public.units(id),
    category    TEXT NOT NULL
                CHECK (category IN ('derrame','dano_propiedad','conducta','no_recoleccion','otro')),
    description TEXT NOT NULL,
    photo_url   TEXT,
    status      TEXT NOT NULL DEFAULT 'open'
                CHECK (status IN ('open','in_review','resolved')),
    created_at  TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_incidents_user ON public.incidents(user_id);
CREATE INDEX IF NOT EXISTS idx_incidents_unit ON public.incidents(unit_id);
