-- Curzon Trucking — Supabase Schema
-- Run this in Supabase → SQL Editor → New Query

-- ── Events (loads) ────────────────────────────────────────────
create table if not exists events (
  id         uuid primary key default gen_random_uuid(),
  summary    text,
  load_num   text,
  ref_nums   text,
  start      text not null,   -- "YYYY-MM-DDTHH:mm" Mountain Time naive
  "end"      text not null,
  rid        integer not null default 0,
  notes      text,
  status     text default '',
  in_alvys   boolean default false,
  created_at timestamptz default now(),
  updated_at timestamptz default now()
);

-- ── Add columns (run once if table already exists) ────────────
alter table events add column if not exists in_alvys   boolean default false;
alter table events add column if not exists detention   boolean default false;
alter table events add column if not exists lumper      boolean default false;

-- ── Index for fast date-range queries ─────────────────────────
-- Run this once if you haven't already:
create index if not exists events_start_rid on events(start, rid);

-- ── Driver overrides (name/unit/truck/color/type edits) ───────
create table if not exists driver_overrides (
  id         integer primary key,  -- matches RESOURCES[].id
  name       text,
  unit       text,
  truck      text,
  color      text,
  type       text,
  updated_at timestamptz default now()
);

-- ── Allow anyone with the anon key to read/write (Phase 1) ────
-- In Phase 2 we'll add proper row-level security + auth
alter table events          enable row level security;
alter table driver_overrides enable row level security;

create policy "public read events"
  on events for select using (true);

create policy "public write events"
  on events for all using (true);

create policy "public read drivers"
  on driver_overrides for select using (true);

create policy "public write drivers"
  on driver_overrides for all using (true);
