-- 001_init.sql — instances and tasks.
--
-- Forward-only. There is no down script. If this is wrong, 002 fixes it.

create table instances (
  id           uuid primary key default gen_random_uuid(),
  team         text        not null,
  service_type text        not null,           -- 'elasticsearch' | 'redis' | ...
  size         text        not null,           -- 'small' | 'medium'
  state        text        not null,
  namespace    text        not null,
  release_name text        not null unique,    -- helm release; the idempotency anchor
  chart_version text       not null,           -- what's ACTUALLY deployed. day-2 hinges on this column.
  endpoint     text,
  error        text,
  expires_at   timestamptz,
  created_at   timestamptz not null default now(),
  updated_at   timestamptz not null default now()
);

create table tasks (
  id            bigserial primary key,
  instance_id   uuid        not null references instances(id) on delete cascade,
  kind          text        not null,          -- 'provision'|'deprovision'|'upgrade'|'verify'
  state         text        not null default 'queued',  -- queued|running|done|failed
  attempts      int         not null default 0,
  run_after     timestamptz not null default now(),     -- backoff lands here
  locked_by     text,
  locked_at     timestamptz,
  last_error    text,
  created_at    timestamptz not null default now()
);

-- Partial index: the claim query only ever looks at queued rows. Keeping the index
-- to that subset means it stays small no matter how much history `tasks` accumulates.
create index tasks_runnable on tasks (run_after) where state = 'queued';
