create table if not exists public.media_assets (
    id uuid primary key default gen_random_uuid(),
    workspace_id uuid not null references public.workspaces(id) on delete cascade,
    document_id uuid not null references public.documents(id) on delete cascade,
    asset_type text not null default 'image',
    file_url text,
    thumbnail_url text,
    ocr_text text,
    ocr_status text default 'pending',
    created_by uuid references public.profiles(id) on delete set null,
    created_at timestamptz not null default timezone('utc', now()),
    updated_at timestamptz not null default timezone('utc', now())
);

create index if not exists media_assets_workspace_idx on public.media_assets (workspace_id, created_at desc);
create index if not exists media_assets_document_idx on public.media_assets (document_id);
create index if not exists media_assets_ocr_text_idx on public.media_assets using gin (to_tsvector('simple', coalesce(ocr_text, '')));

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

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

alter table public.media_assets enable row level security;

drop policy if exists "Select assets within workspace" on public.media_assets;
create policy "Select assets within workspace"
    on public.media_assets
    for select
    using (
        exists (
            select 1
            from public.workspace_members wm
            where wm.workspace_id = media_assets.workspace_id
              and wm.user_id = auth.uid()
        )
    );

drop policy if exists "Insert assets within workspace" on public.media_assets;
create policy "Insert assets within workspace"
    on public.media_assets
    for insert
    with check (
        exists (
            select 1
            from public.workspace_members wm
            where wm.workspace_id = media_assets.workspace_id
              and wm.user_id = auth.uid()
        )
    );

drop policy if exists "Update assets within workspace" on public.media_assets;
create policy "Update assets within workspace"
    on public.media_assets
    for update
    using (
        exists (
            select 1
            from public.workspace_members wm
            where wm.workspace_id = media_assets.workspace_id
              and wm.user_id = auth.uid()
        )
    )
    with check (
        exists (
            select 1
            from public.workspace_members wm
            where wm.workspace_id = media_assets.workspace_id
              and wm.user_id = auth.uid()
        )
    );
