-- Migration: v79-creator-codes.sql
-- Creator and referral codes with custom rewards (3-day premium trial, image hosting, custom badges)

create table if not exists public.creator_codes (
  id uuid primary key default gen_random_uuid(),
  code text not null unique,
  creator_name text not null,
  creator_profile_id uuid references public.profiles(id) on delete set null,
  creator_discord_id text,
  trial_days integer not null default 3,
  badge_id text,
  badge_name text,
  badge_icon text,
  max_uses integer,
  uses_count integer not null default 0,
  is_active boolean not null default true,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

create table if not exists public.creator_code_redemptions (
  id uuid primary key default gen_random_uuid(),
  code_id uuid not null references public.creator_codes(id) on delete cascade,
  profile_id uuid not null references public.profiles(id) on delete cascade,
  trial_days_granted integer not null default 3,
  badge_granted text,
  ip_hash text,
  redeemed_at timestamptz not null default now(),
  unique(code_id, profile_id)
);

alter table public.creator_codes enable row level security;
alter table public.creator_code_redemptions enable row level security;

drop policy if exists "creator_codes_read" on public.creator_codes;
create policy "creator_codes_read" on public.creator_codes for select using (true);

drop policy if exists "creator_code_redemptions_read_own" on public.creator_code_redemptions;
create policy "creator_code_redemptions_read_own" on public.creator_code_redemptions for select using (auth.uid() = profile_id);
