create extension if not exists pgcrypto;

create table if not exists public.generations (
  id uuid primary key default gen_random_uuid(),
  user_id text not null,
  destination_url text not null,
  qr_mode text not null check (qr_mode in ('standard', 'artistic')),
  preset_id text,
  prompt text not null,
  status text not null default 'mocked' check (status in ('queued', 'processing', 'completed', 'failed', 'mocked')),
  credit_cost integer not null default 1 check (credit_cost > 0),
  created_at timestamptz not null default now()
);

create table if not exists public.generation_variants (
  id uuid primary key default gen_random_uuid(),
  generation_id uuid not null references public.generations(id) on delete cascade,
  variant_index integer not null,
  image_url text,
  thumbnail_url text,
  metadata jsonb not null default '{}'::jsonb,
  created_at timestamptz not null default now(),
  unique (generation_id, variant_index)
);

create index if not exists generations_user_id_created_at_idx
  on public.generations(user_id, created_at desc);

create index if not exists generation_variants_generation_id_idx
  on public.generation_variants(generation_id);
