create table if not exists public.wg_gallery_photos (
    id uuid primary key default gen_random_uuid(),
    unsplash_id text not null unique,
    slug text,
    description text,
    alt_description text,
    width integer,
    height integer,
    color text,
    blur_hash text,
    likes integer,
    photo_created_at timestamptz,
    photo_updated_at timestamptz,
    urls jsonb not null default '{}'::jsonb,
    links jsonb not null default '{}'::jsonb,
    user_info jsonb not null default '{}'::jsonb,
    raw jsonb not null,
    source text not null default 'unsplash-wallpapers',
    created_at timestamptz not null default now(),
    updated_at timestamptz not null default now()
);

create table if not exists public.wg_gallery_sync_state (
    source text primary key,
    next_page integer not null default 1,
    per_page integer not null default 20,
    last_synced_at timestamptz,
    last_inserted_count integer not null default 0,
    last_seen_count integer not null default 0,
    last_error text,
    updated_at timestamptz not null default now()
);

create index if not exists wg_gallery_photos_source_created_at_idx
    on public.wg_gallery_photos (source, created_at desc);

create index if not exists wg_gallery_photos_photo_created_at_idx
    on public.wg_gallery_photos (photo_created_at desc);

alter table public.wg_gallery_photos enable row level security;
alter table public.wg_gallery_sync_state enable row level security;

drop policy if exists "Public can read gallery photos" on public.wg_gallery_photos;
create policy "Public can read gallery photos"
    on public.wg_gallery_photos
    for select
    to anon, authenticated
    using (true);

drop trigger if exists set_wg_gallery_photos_updated_at on public.wg_gallery_photos;
drop trigger if exists set_wg_gallery_sync_state_updated_at on public.wg_gallery_sync_state;
drop function if exists public.set_wg_updated_at();

create function public.set_wg_updated_at()
returns trigger
language plpgsql
set search_path = public
as $$
begin
    new.updated_at = now();
    return new;
end;
$$;

create trigger set_wg_gallery_photos_updated_at
    before update on public.wg_gallery_photos
    for each row
    execute function public.set_wg_updated_at();

create trigger set_wg_gallery_sync_state_updated_at
    before update on public.wg_gallery_sync_state
    for each row
    execute function public.set_wg_updated_at();
