create table if not exists public.background_tasks (
    id uuid primary key default gen_random_uuid(),
    user_id uuid not null references auth.users (id) on delete cascade,
    document_id uuid references public.documents (id) on delete cascade,
    task_type text not null default 'ocr',
    status text not null default 'pending',
    progress integer not null default 0 check (progress between 0 and 100),
    message text,
    created_at timestamptz not null default timezone('utc', now()),
    updated_at timestamptz not null default timezone('utc', now())
);

create index if not exists background_tasks_user_idx
    on public.background_tasks (user_id, created_at desc);

create index if not exists background_tasks_document_idx
    on public.background_tasks (document_id, created_at desc);

create or replace function public.set_background_tasks_updated_at()
returns trigger
language plpgsql
security invoker
as $$
begin
    new.updated_at := timezone('utc', now());
    return new;
end;
$$;

drop trigger if exists set_background_tasks_updated_at on public.background_tasks;
create trigger set_background_tasks_updated_at
before update on public.background_tasks
for each row
execute procedure public.set_background_tasks_updated_at();

alter table public.background_tasks enable row level security;

drop policy if exists "Own background tasks" on public.background_tasks;
create policy "Own background tasks"
    on public.background_tasks
    for all
    using (auth.uid() = user_id)
    with check (auth.uid() = user_id);
