create table if not exists public.user_recent_pages (
    id uuid primary key default gen_random_uuid(),
    user_id uuid not null references public.profiles(id) on delete cascade,
    workspace_id uuid not null references public.workspaces(id) on delete cascade,
    document_id uuid not null references public.documents(id) on delete cascade,
    last_accessed_at timestamptz not null default timezone('utc', now())
);

create unique index if not exists user_recent_pages_user_document_idx
    on public.user_recent_pages (user_id, document_id);

create index if not exists user_recent_pages_workspace_idx
    on public.user_recent_pages (workspace_id, last_accessed_at desc);

alter table public.user_recent_pages enable row level security;

drop policy if exists "Recent pages are visible to owner" on public.user_recent_pages;
create policy "Recent pages are visible to owner"
    on public.user_recent_pages
    for select
    using (user_id = auth.uid());

drop policy if exists "Upsert recent pages for owner" on public.user_recent_pages;
create policy "Upsert recent pages for owner"
    on public.user_recent_pages
    for all
    using (user_id = auth.uid())
    with check (user_id = auth.uid());
