-- ============================================================
-- clauth machine enrollment
-- Migration: 003_machine_enrollments.sql
-- ============================================================

alter table public.clauth_machines
  add column if not exists install_id text not null default 'default';

create index if not exists clauth_machines_install_id_idx
  on public.clauth_machines (install_id);

create table if not exists public.clauth_machine_enrollments (
  id uuid primary key default gen_random_uuid(),
  install_id text not null default 'default',
  token_hash text not null unique,
  label text,
  created_by_machine_hash text not null references public.clauth_machines(machine_hash) on delete cascade,
  redeemed_by_machine_hash text references public.clauth_machines(machine_hash) on delete set null,
  expires_at timestamptz not null,
  consumed_at timestamptz,
  created_at timestamptz not null default now()
);

create index if not exists clauth_machine_enrollments_install_idx
  on public.clauth_machine_enrollments (install_id, expires_at);

alter table public.clauth_machine_enrollments enable row level security;

do $$ begin
  if not exists (
    select 1
    from pg_policies
    where policyname = 'no_anon_machine_enrollments'
      and tablename = 'clauth_machine_enrollments'
  ) then
    create policy "no_anon_machine_enrollments"
      on public.clauth_machine_enrollments for all using (false);
  end if;
end $$;
