-- Video render job queue (run in Supabase SQL Editor)
-- Also create Storage bucket "renders" (public) in Dashboard → Storage

create table if not exists public.render_jobs (
  id uuid primary key default gen_random_uuid(),
  project_id text not null,
  status text not null default 'queued'
    check (status in ('queued', 'processing', 'completed', 'failed')),
  progress integer not null default 0 check (progress >= 0 and progress <= 100),
  progress_message text,
  output_url text,
  scenes jsonb not null,
  settings jsonb not null,
  error_message text,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

create index if not exists render_jobs_project_id_idx
  on public.render_jobs (project_id);

create index if not exists render_jobs_status_idx
  on public.render_jobs (status);

alter table public.render_jobs enable row level security;

-- Service role bypasses RLS; allow authenticated read via API routes only.
create policy "Authenticated users can read render jobs"
  on public.render_jobs
  for select
  to authenticated
  using (true);

create or replace function public.set_render_jobs_updated_at()
returns trigger
language plpgsql
as $$
begin
  new.updated_at = now();
  return new;
end;
$$;

drop trigger if exists render_jobs_updated_at on public.render_jobs;

create trigger render_jobs_updated_at
  before update on public.render_jobs
  for each row
  execute function public.set_render_jobs_updated_at();
