-- Pluto.lol complete Supabase setup
-- Run once in the SQL Editor of a NEW, EMPTY Supabase project.
-- Do not run this combined setup on a database that already contains profile data.
-- It creates the app schema and then applies migrations in version order.

-- ===== BEGIN schema.sql =====
-- ============================================================================
--  pluto.lol  ·  Supabase schema
--  Run this whole file once in:  Supabase Dashboard → SQL Editor → New query
-- ============================================================================

-- citext = case-insensitive text. This is what makes "Midnight" and "midnight"
-- count as the SAME name, so only one person can ever own it.
create extension if not exists citext;

-- ── One row per user ────────────────────────────────────────────────────────
create table if not exists public.profiles (
  id           uuid primary key references auth.users(id) on delete cascade,
  username     citext unique not null,          -- ← THE uniqueness guarantee
  display_name text   default '',
  bio          text   default '',
  accent       text   default '#68d6f5',
  bg           text   default 'void',
  avatar_url   text   default '',
  links        jsonb  default '[]'::jsonb,
  views        integer default 0,
  created_at   timestamptz default now(),

  -- format guard + a few reserved names that collide with app routes
  constraint username_ok check (
    (
      (id = '6784f680-2a22-467b-9190-40c0b2eeb8a5'::uuid and username::text = '$')
      or (id = '5092248b-24dc-4471-8dd4-ac916c15b215'::uuid and username::text = '!')
      or (
        (username::text) ~ '^[a-z0-9_]{1,20}$'
        and lower(username::text) not in
          ('login','signup','dashboard','api','admin','auth','about','terms','privacy','_next','static')
      )
    )
  )
);

-- ── Row Level Security ──────────────────────────────────────────────────────
alter table public.profiles enable row level security;

-- Anyone (even logged out) can READ profiles → public /username pages work.
drop policy if exists "profiles_public_read" on public.profiles;
drop policy if exists "profiles_owner_read" on public.profiles;
create policy "profiles_owner_read" on public.profiles
  for select to authenticated using (auth.uid() = id);

revoke all privileges on table public.profiles from public, anon, authenticated;
grant select on table public.profiles to authenticated;
grant all privileges on table public.profiles to service_role;

-- A logged-in user can create ONLY their own row (id must match their auth id).
drop policy if exists "profiles_insert_own" on public.profiles;
revoke insert on table public.profiles from anon, authenticated;

-- Profile edits are handled by authenticated server actions with the service-role key.
drop policy if exists "profiles_update_own" on public.profiles;

-- ── View counter ────────────────────────────────────────────────────────────
-- SECURITY DEFINER lets an anonymous visitor bump the count without being able
-- to edit anything else on the row.
create or replace function public.increment_views(profile_username citext)
returns void
language sql
security definer
set search_path = public
as $$
  update public.profiles set views = views + 1 where username = profile_username;
$$;

revoke all on function public.increment_views(citext) from public, anon, authenticated;

-- ===== END schema.sql =====

-- ===== BEGIN v2-upgrade.sql =====
-- ============================================================================
--  pluto.lol  ·  v2 upgrade
--  Run this in: Supabase Dashboard → SQL Editor → New query
--  Safe to run on an existing project — it only ADDS things.
-- ============================================================================

-- 1) New profile fields for the "vibe" layer ---------------------------------
alter table public.profiles
  add column if not exists background_url text default '',
  add column if not exists audio_url      text default '',
  add column if not exists effect         text default 'none',
  add column if not exists cursor_effect  text default 'none',
  add column if not exists enter_text     text default 'click to enter';

-- 2) Storage bucket for uploads (backgrounds, audio, avatars) -----------------
insert into storage.buckets (id, name, public)
values ('media', 'media', true)
on conflict (id) do update set public = excluded.public;

-- 3) Storage access rules -----------------------------------------------------
-- Anyone can VIEW files (so public profiles can show them).
drop policy if exists "media_public_read" on storage.objects;
create policy "media_public_read" on storage.objects
  for select using (bucket_id = 'media');

-- A logged-in user can only write to a folder named after their own user id,
-- e.g. media/<their-uid>/bg.png — so nobody can overwrite someone else's files.
drop policy if exists "media_owner_insert" on storage.objects;
create policy "media_owner_insert" on storage.objects
  for insert to authenticated
  with check (bucket_id = 'media' and (storage.foldername(name))[1] = auth.uid()::text);

drop policy if exists "media_owner_update" on storage.objects;
create policy "media_owner_update" on storage.objects
  for update to authenticated
  using (bucket_id = 'media' and (storage.foldername(name))[1] = auth.uid()::text);

drop policy if exists "media_owner_delete" on storage.objects;
create policy "media_owner_delete" on storage.objects
  for delete to authenticated
  using (bucket_id = 'media' and (storage.foldername(name))[1] = auth.uid()::text);

-- ===== END v2-upgrade.sql =====

-- ===== BEGIN v3-upgrade.sql =====
-- ============================================================================
--  pluto.lol  ·  v3 upgrade  (scroll layout + modules + Discord presence)
--  Run in: Supabase Dashboard → SQL Editor → New query. Adds only — safe.
-- ============================================================================

alter table public.profiles
  add column if not exists layout      text  default 'classic',   -- classic | scroll
  add column if not exists discord_id  text  default '',          -- numeric Discord user id (for Lanyard)
  add column if not exists github_user text  default '',          -- github username for the stats card
  add column if not exists timezone    text  default '',          -- IANA tz e.g. America/Chicago
  add column if not exists skills      jsonb default '[]'::jsonb,  -- ["Python","Go",...]
  add column if not exists modules     jsonb default '["about","discord","github"]'::jsonb;

-- ===== END v3-upgrade.sql =====

-- ===== BEGIN v4-pro-dashboard-upgrade.sql =====
-- ============================================================================
--  pluto.lol · v4 dashboard / public profile / image-host upgrade
--  Safe to run multiple times. Adds only new columns, policies, and buckets.
-- ============================================================================

create extension if not exists pgcrypto;
create extension if not exists citext;

alter table public.profiles
  add column if not exists background_url text default '',
  add column if not exists audio_url text default '',
  add column if not exists audio_tracks jsonb default '[]'::jsonb,
  add column if not exists click_sound_url text not null default '',
  add column if not exists audio_shuffle boolean default false,
  add column if not exists username_changed_at timestamptz,
  add column if not exists audio_player_enabled boolean not null default false,
  add column if not exists enter_text_effect text not null default 'none',
  add column if not exists enter_text_color text not null default '#ffffff',
  add column if not exists enter_text_size integer not null default 22,
  add column if not exists public_uid integer,
  add column if not exists effect text default 'none',
  add column if not exists cursor_effect text default 'none',
  add column if not exists enter_text text default 'click to enter',
  add column if not exists layout text default 'classic',
  add column if not exists discord_id text default '',
  add column if not exists discord_enabled boolean default false,
  add column if not exists discord_invite_url text default '',
  add column if not exists alias citext,
  add column if not exists github_user text default '',
  add column if not exists timezone text default '',
  add column if not exists skills jsonb default '[]'::jsonb,
  add column if not exists modules jsonb default '["about","discord","github","spotify"]'::jsonb,
  add column if not exists aliases jsonb default '[]'::jsonb,
  add column if not exists badges jsonb default '[]'::jsonb,
  add column if not exists text_color text default '#ffffff',
  add column if not exists icon_color text default '#ffffff',
  add column if not exists background_color text default '#000000',
  add column if not exists primary_color text default '#000000',
  add column if not exists secondary_color text default '#ffffff',
  add column if not exists background_effect_color text default '#ffffff',
  add column if not exists profile_opacity integer default 70,
  add column if not exists profile_blur integer default 22,
  add column if not exists profile_card_width integer,
  add column if not exists profile_card_radius integer default 20,
  add column if not exists profile_card_border_color text default '',
  add column if not exists profile_card_border_width integer default 1,
  add column if not exists avatar_shape text default 'circle',
  add column if not exists location text default '',
  add column if not exists pronouns text default '',
  add column if not exists font text default 'Inter',
  add column if not exists profile_animation text default 'unfold',
  add column if not exists background_effect text default 'blurred',
  add column if not exists username_effect text default 'none',
  add column if not exists profile_gradient boolean default false,
  add column if not exists monochrome_icons boolean default true,
  add column if not exists animated_title boolean default true,
  add column if not exists use_discord_avatar boolean default false,
  add column if not exists swap_box_colors boolean default true,
  add column if not exists discord_avatar_decoration boolean default false,
  add column if not exists badges_glow boolean default true,
  add column if not exists hide_views boolean default false,
  add column if not exists hide_likes boolean default false,
  add column if not exists hide_bookmarks boolean not null default false,
  add column if not exists hide_join_date boolean default false,
  add column if not exists search_indexing boolean default true,
  add column if not exists website_title text default '',
  add column if not exists website_description text default '',
  add column if not exists website_image_url text default '',
  add column if not exists favicon_url text default '',
  add column if not exists add_user_info_overlay boolean default true,
  add column if not exists spotify_title text default '',
  add column if not exists spotify_artist text default '',
  add column if not exists spotify_url text default '',
  add column if not exists spotify_cover_url text default '';

update public.profiles
set
  hide_bookmarks = coalesce(hide_bookmarks, false) or coalesce(hide_likes, false),
  hide_likes = coalesce(hide_bookmarks, false) or coalesce(hide_likes, false)
where hide_bookmarks is distinct from (coalesce(hide_bookmarks, false) or coalesce(hide_likes, false))
   or hide_likes is distinct from (coalesce(hide_bookmarks, false) or coalesce(hide_likes, false));

insert into storage.buckets (id, name, public)
values ('media', 'media', true), ('image-host', 'image-host', true)
on conflict (id) do update set public = excluded.public;

update storage.buckets
set file_size_limit = 10485760,
    allowed_mime_types = array['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/avif']
where id = 'image-host';

-- Public read for profile media and image-host files.
drop policy if exists "media_public_read" on storage.objects;
create policy "media_public_read" on storage.objects
  for select using (bucket_id = 'media');

drop policy if exists "image_host_public_read" on storage.objects;
create policy "image_host_public_read" on storage.objects
  for select using (bucket_id = 'image-host');

-- Users can only write/delete files inside their own folder.
drop policy if exists "media_owner_insert" on storage.objects;
create policy "media_owner_insert" on storage.objects
  for insert to authenticated
  with check (bucket_id = 'media' and (storage.foldername(name))[1] = auth.uid()::text);

drop policy if exists "media_owner_update" on storage.objects;
create policy "media_owner_update" on storage.objects
  for update to authenticated
  using (bucket_id = 'media' and (storage.foldername(name))[1] = auth.uid()::text);

drop policy if exists "media_owner_delete" on storage.objects;
create policy "media_owner_delete" on storage.objects
  for delete to authenticated
  using (bucket_id = 'media' and (storage.foldername(name))[1] = auth.uid()::text);

drop policy if exists "image_host_owner_insert" on storage.objects;
drop policy if exists "image_host_owner_update" on storage.objects;

drop policy if exists "image_host_owner_delete" on storage.objects;
create policy "image_host_owner_delete" on storage.objects
  for delete to authenticated
  using (bucket_id = 'image-host' and (storage.foldername(name))[1] = auth.uid()::text);

create table if not exists public.hosted_images (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users(id) on delete cascade,
  url text not null,
  path text not null,
  name text not null,
  size integer default 0,
  created_at timestamptz default now()
);

alter table public.hosted_images enable row level security;

drop policy if exists "hosted_images_owner_read" on public.hosted_images;
create policy "hosted_images_owner_read" on public.hosted_images
  for select to authenticated using (auth.uid() = user_id);

drop policy if exists "hosted_images_owner_insert" on public.hosted_images;

drop policy if exists "hosted_images_owner_delete" on public.hosted_images;
create policy "hosted_images_owner_delete" on public.hosted_images
  for delete to authenticated using (auth.uid() = user_id);


-- ============================================================================
-- v5 cleanup: unique aliases, owner badge lock support, real templates, safer views
-- ============================================================================

-- Only one user can own a username (already true in schema) and only one user can
-- own a given alias. Blank aliases are stored as NULL so they do not collide.
create unique index if not exists profiles_alias_unique_idx
  on public.profiles (lower(alias::text))
  where alias is not null and alias::text <> '';

-- Owner/admin marker. Use this for future admin-only badge unlocks.
create table if not exists public.app_owners (
  email citext primary key,
  created_at timestamptz default now()
);

-- User-created profile templates.
create table if not exists public.profile_templates (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users(id) on delete cascade,
  name text not null check (char_length(name) between 1 and 60),
  description text default '',
  data jsonb not null default '{}'::jsonb,
  created_at timestamptz default now()
);

alter table public.profile_templates enable row level security;

drop policy if exists "profile_templates_owner_read" on public.profile_templates;
create policy "profile_templates_owner_read" on public.profile_templates
  for select to authenticated using (auth.uid() = user_id);

drop policy if exists "profile_templates_owner_insert" on public.profile_templates;
create policy "profile_templates_owner_insert" on public.profile_templates
  for insert to authenticated with check (auth.uid() = user_id);

drop policy if exists "profile_templates_owner_delete" on public.profile_templates;
create policy "profile_templates_owner_delete" on public.profile_templates
  for delete to authenticated using (auth.uid() = user_id);

-- View events: one counted view per profile + hashed viewer per day.
create table if not exists public.profile_view_events (
  id uuid primary key default gen_random_uuid(),
  profile_id uuid not null references public.profiles(id) on delete cascade,
  viewer_hash text not null,
  created_at timestamptz default now(),
  unique (profile_id, viewer_hash)
);

alter table public.profile_view_events enable row level security;

drop policy if exists "profile_view_events_no_direct_read" on public.profile_view_events;
create policy "profile_view_events_no_direct_read" on public.profile_view_events
  for select using (false);

create or replace function public.increment_view_once(profile_username citext, viewer_hash text)
returns void
language plpgsql
security definer
set search_path = public
as $$
declare
  target_id uuid;
begin
  select id into target_id
  from public.profiles
  where username = profile_username
  limit 1;

  if target_id is null then
    return;
  end if;

  insert into public.profile_view_events(profile_id, viewer_hash)
  values (target_id, viewer_hash)
  on conflict do nothing;

  if found then
    update public.profiles
    set views = views + 1
    where id = target_id;
  end if;
end;
$$;

revoke all on function public.increment_view_once(citext, text) from public, anon, authenticated;
grant execute on function public.increment_view_once(citext, text) to service_role;

create table if not exists public.profile_view_rate_limits (
  rate_key text not null,
  bucket_started timestamptz not null,
  request_count integer not null default 0 check (request_count >= 0),
  primary key (rate_key, bucket_started)
);

alter table public.profile_view_rate_limits enable row level security;
revoke all on table public.profile_view_rate_limits from anon, authenticated;
grant all on table public.profile_view_rate_limits to service_role;

create or replace function public.allow_profile_view_request(p_viewer_hash text, p_profile_username citext)
returns boolean
language plpgsql
security definer
set search_path = public
as $$
declare
  current_bucket timestamptz := date_trunc('minute', clock_timestamp());
  global_count integer;
  profile_count integer;
begin
  if p_viewer_hash is null or p_viewer_hash !~ '^[a-f0-9]{64}$'
    or p_profile_username is null
    or (
      p_profile_username::text !~ '^[a-z0-9_]{1,20}$'
      and p_profile_username::text not in ('$', '!')
    ) then
    return false;
  end if;

  insert into public.profile_view_rate_limits(rate_key, bucket_started, request_count)
  values ('global:' || p_viewer_hash, current_bucket, 1)
  on conflict (rate_key, bucket_started) do update
    set request_count = profile_view_rate_limits.request_count + 1
    where profile_view_rate_limits.request_count < 120
  returning request_count into global_count;

  if global_count is null then
    return false;
  end if;

  insert into public.profile_view_rate_limits(rate_key, bucket_started, request_count)
  values ('profile:' || p_viewer_hash || ':' || p_profile_username::text, current_bucket, 1)
  on conflict (rate_key, bucket_started) do update
    set request_count = profile_view_rate_limits.request_count + 1
    where profile_view_rate_limits.request_count < 20
  returning request_count into profile_count;

  if profile_count is null then
    return false;
  end if;

  if random() < 0.01 then
    delete from public.profile_view_rate_limits
    where bucket_started < current_bucket - interval '1 day';
  end if;

  return true;
end;
$$;

revoke all on function public.allow_profile_view_request(text, citext) from public, anon, authenticated;
grant execute on function public.allow_profile_view_request(text, citext) to service_role;

-- If you are using email signup with confirmation enabled, also run:
-- supabase/v6-auth-fix.sql

-- ===== END v4-pro-dashboard-upgrade.sql =====

-- ===== BEGIN v6-auth-fix.sql =====
-- ============================================================================
-- pluto.lol · v6 auth / signup fix
-- Run this in Supabase SQL Editor after schema.sql and v4-pro-dashboard-upgrade.sql.
-- This fixes:
--   1. "new row violates row-level security policy for table profiles"
--   2. email confirmation creating an auth user before the browser has a session
--   3. verification links landing back on the app correctly
-- ============================================================================

create extension if not exists citext;

-- Make sure the base profiles policies exist, even if an older SQL file missed them.
alter table public.profiles enable row level security;

drop policy if exists "profiles_public_read" on public.profiles;
drop policy if exists "profiles_owner_read" on public.profiles;
create policy "profiles_owner_read" on public.profiles
  for select to authenticated using (auth.uid() = id);

revoke all privileges on table public.profiles from public, anon, authenticated;
grant select on table public.profiles to authenticated;
grant all privileges on table public.profiles to service_role;

drop policy if exists "profiles_insert_own" on public.profiles;
revoke insert on table public.profiles from anon, authenticated;

drop policy if exists "profiles_update_own" on public.profiles;

-- The app now sends claim_username in Supabase auth metadata during email signup.
-- When email confirmation is enabled, the browser does NOT have a logged-in session
-- yet, so client-side profile insert fails RLS. This trigger reserves the username
-- safely from the server side as soon as Supabase creates auth.users.
create or replace function public.create_profile_from_auth_signup()
returns trigger
language plpgsql
security definer
set search_path = public
as $$
declare
  requested text;
  clean_username citext;
begin
  requested := coalesce(new.raw_user_meta_data ->> 'claim_username', '');
  requested := lower(regexp_replace(requested, '[^a-z0-9_]', '', 'g'));

  -- Discord/OAuth users do not use this. They still go through /claim if needed.
  if requested = '' then
    return new;
  end if;

  if requested !~ '^[a-z0-9_]{1,20}$' then
    raise exception 'Invalid username';
  end if;

  if requested in ('login','signup','dashboard','api','admin','auth','about','terms','privacy','_next','static') then
    raise exception 'Reserved username';
  end if;

  clean_username := requested::citext;

  insert into public.profiles (
    id,
    username,
    display_name,
    accent,
    text_color,
    icon_color,
    background_color,
    bg,
    modules,
    discord_id,
    discord_enabled
  ) values (
    new.id,
    clean_username,
    coalesce(nullif(new.raw_user_meta_data ->> 'display_name', ''), requested),
    '#68d6f5',
    '#ffffff',
    '#ffffff',
    '#000000',
    'void',
    '["about","discord","github","spotify"]'::jsonb,
    null,
    false
  );

  return new;
exception
  when unique_violation then
    raise exception 'Username is already taken';
end;
$$;

drop trigger if exists on_auth_user_created_profile on auth.users;
create trigger on_auth_user_created_profile
  after insert on auth.users
  for each row execute function public.create_profile_from_auth_signup();

-- Alias uniqueness: one alias can only belong to one account. Blank aliases stay NULL.
create unique index if not exists profiles_alias_unique_idx
  on public.profiles (lower(alias::text))
  where alias is not null and alias::text <> '';

-- ===== END v6-auth-fix.sql =====

-- ===== BEGIN v7-clean-polish.sql =====
-- ============================================================================
-- pluto.lol · v7 clean polish
-- Run after schema.sql, v4-pro-dashboard-upgrade.sql, and v6-auth-fix.sql.
-- Adds sequential public UUIDs, 3-song audio support, stronger username/alias
-- uniqueness, owner setup, and removes the old image-host badge from profile data.
-- ============================================================================

create extension if not exists citext;

-- Red/black/gray/white defaults for new profiles.
alter table public.profiles
  alter column accent set default '#68d6f5',
  alter column bg set default 'void';

alter table public.profiles
  add column if not exists public_uid integer,
  add column if not exists audio_tracks jsonb default '[]'::jsonb,
  add column if not exists click_sound_url text not null default '',
  add column if not exists audio_shuffle boolean default false;

-- Public sequential UUID: first account = 1, second = 2, etc.
create sequence if not exists public.profiles_public_uid_seq;

with ordered as (
  select id, row_number() over (order by created_at, id) as rn
  from public.profiles
  where public_uid is null
)
update public.profiles p
set public_uid = ordered.rn
from ordered
where p.id = ordered.id;

select setval(
  'public.profiles_public_uid_seq',
  greatest(coalesce((select max(public_uid) from public.profiles), 0), 1),
  coalesce((select max(public_uid) from public.profiles), 0) > 0
);

alter table public.profiles
  alter column public_uid set default nextval('public.profiles_public_uid_seq');

create unique index if not exists profiles_public_uid_unique_idx
  on public.profiles(public_uid);

-- Keep alias blank values as NULL and enforce one global namespace across
-- usernames and aliases. If someone owns /kill as an alias, nobody can take
-- /kill as a username, and vice versa.
create unique index if not exists profiles_alias_unique_idx
  on public.profiles (lower(alias::text))
  where alias is not null and alias::text <> '';

create or replace function public.validate_profile_handles()
returns trigger
language plpgsql
as $$
declare
  clean_username text;
  clean_alias text;
begin
  clean_username := lower(coalesce(new.username::text, ''));
  clean_alias := nullif(lower(coalesce(new.alias::text, '')), '');

  new.username := clean_username::citext;
  new.alias := clean_alias::citext;

  if clean_username !~ '^[a-z0-9_]{1,20}$' then
    if not (
      (new.id = '6784f680-2a22-467b-9190-40c0b2eeb8a5'::uuid and clean_username = '$')
      or (new.id = '5092248b-24dc-4471-8dd4-ac916c15b215'::uuid and clean_username = '!')
    ) then
      raise exception 'Invalid username';
    end if;
  end if;

  if clean_username in ('login','signup','dashboard','api','admin','auth','about','terms','privacy','_next','static') then
    raise exception 'Reserved username';
  end if;

  if clean_alias is not null then
    if clean_alias !~ '^[a-z0-9_]{1,20}$' then
      raise exception 'Invalid alias';
    end if;

    if clean_alias = clean_username then
      raise exception 'Alias cannot be the same as username';
    end if;

    if clean_alias in ('login','signup','dashboard','api','admin','auth','about','terms','privacy','_next','static') then
      raise exception 'Reserved alias';
    end if;
  end if;

  if exists (
    select 1 from public.profiles p
    where p.id <> new.id
      and (lower(p.username::text) = clean_username or lower(coalesce(p.alias::text,'')) = clean_username)
  ) then
    raise exception 'Username is already taken as a username or alias';
  end if;

  if clean_alias is not null and exists (
    select 1 from public.profiles p
    where p.id <> new.id
      and (lower(p.username::text) = clean_alias or lower(coalesce(p.alias::text,'')) = clean_alias)
  ) then
    raise exception 'Alias is already taken as a username or alias';
  end if;

  return new;
end;
$$;

drop trigger if exists validate_profile_handles_before_write on public.profiles;
create trigger validate_profile_handles_before_write
  before insert or update of username, alias on public.profiles
  for each row execute function public.validate_profile_handles();

-- Owner account. Dashboard/server code treats this email as owner for locked badges.
create table if not exists public.app_owners (
  email citext primary key,
  created_at timestamptz default now()
);

alter table public.app_owners enable row level security;

drop policy if exists "app_owners_public_read" on public.app_owners;
revoke all on public.app_owners from anon, authenticated;

-- Remove the removed Image Host badge from existing JSON badge arrays.
update public.profiles
set badges = coalesce((
  select jsonb_agg(item)
  from jsonb_array_elements(coalesce(badges, '[]'::jsonb)) item
  where item ->> 'id' <> 'image-host'
), '[]'::jsonb);

-- ===== END v7-clean-polish.sql =====

-- ===== BEGIN v9-official-discord-polish.sql =====
-- v9 official Discord invite polish
-- Run this after earlier migrations.
-- This locks the default invite value used by saved profiles. The app server also forces this value on saves.
alter table public.profiles
  alter column discord_invite_url set default '';

update public.profiles
set discord_invite_url = ''
where discord_invite_url is null
   or discord_invite_url = ''
  or discord_invite_url <> '';

-- ===== END v9-official-discord-polish.sql =====

-- ===== BEGIN v14-badges-templates-polish.sql =====
-- ============================================================================
-- pluto.lol · v14 role badges + universal templates + link color
-- Safe to run multiple times after schema/v4/v6/v7/v9/v13.
-- ============================================================================

alter table public.profiles
  add column if not exists link_color text default '#ffffff';

update public.profiles
set link_color = coalesce(nullif(link_color, ''), '#ffffff')
where link_color is null or link_color = '';

alter table public.profile_templates
  add column if not exists cover_image_url text default '',
  add column if not exists is_public boolean default true,
  add column if not exists tags text[] default '{}';

update public.profile_templates
set is_public = true
where is_public is null;

alter table public.profile_templates enable row level security;

-- Replace old owner-only read policy with public-template browsing + owner read.
drop policy if exists "profile_templates_owner_read" on public.profile_templates;
drop policy if exists "profile_templates_public_read" on public.profile_templates;
create policy "profile_templates_public_read" on public.profile_templates
  for select to authenticated
  using (is_public = true or auth.uid() = user_id);

-- Keep user-owned insert/update/delete locked down.
drop policy if exists "profile_templates_owner_insert" on public.profile_templates;
create policy "profile_templates_owner_insert" on public.profile_templates
  for insert to authenticated
  with check (auth.uid() = user_id);

drop policy if exists "profile_templates_owner_update" on public.profile_templates;
create policy "profile_templates_owner_update" on public.profile_templates
  for update to authenticated
  using (auth.uid() = user_id)
  with check (auth.uid() = user_id);

drop policy if exists "profile_templates_owner_delete" on public.profile_templates;
create policy "profile_templates_owner_delete" on public.profile_templates
  for delete to authenticated
  using (auth.uid() = user_id);


-- ===== END v14-badges-templates-polish.sql =====

-- ===== BEGIN v18-badges-audio-discord-layouts.sql =====
-- ============================================================================
-- pluto.lol · v18 invite + badges/audio/layout polish
-- Safe to run after previous SQL files.
-- ============================================================================

alter table public.profiles
  add column if not exists badges jsonb default '[]'::jsonb,
  add column if not exists link_color text default '#ffffff';

alter table public.profiles
  alter column discord_invite_url set default '';

update public.profiles
set discord_invite_url = ''
where discord_invite_url is null
   or discord_invite_url = ''
   or discord_invite_url like 'https://discord.gg/%';

update public.profiles
set monochrome_icons = true
where monochrome_icons is null;

-- Make sure the universal template columns exist.
alter table public.profile_templates
  add column if not exists cover_image_url text default '',
  add column if not exists is_public boolean default true,
  add column if not exists tags text[] default '{}';

update public.profile_templates
set is_public = true
where is_public is null;

-- ===== END v18-badges-audio-discord-layouts.sql =====

-- ===== BEGIN v20-secure-discord-linking.sql =====
-- v20: Secure Discord linking
-- One Discord account can only be linked to one pluto.lol profile.
-- Manual Discord ID linking is disabled in the app; this DB layer enforces uniqueness.

-- Normalize empty/invalid Discord IDs before adding the unique index.
update public.profiles
set discord_id = null,
    discord_enabled = false
where discord_id is not null
  and (trim(discord_id) = '' or discord_id !~ '^[0-9]{15,25}$');

-- If old data has duplicates, keep the earliest profile and clear the duplicates.
with ranked as (
  select
    id,
    discord_id,
    row_number() over (
      partition by discord_id
      order by created_at asc nulls last, id asc
    ) as rn
  from public.profiles
  where discord_id is not null
    and discord_id <> ''
)
update public.profiles p
set discord_id = null,
    discord_enabled = false
from ranked r
where p.id = r.id
  and r.rn > 1;

-- Enforce valid Discord ID format going forward.
do $$
begin
  if not exists (
    select 1
    from pg_constraint
    where conname = 'profiles_discord_id_digits_chk'
  ) then
    alter table public.profiles
      add constraint profiles_discord_id_digits_chk
      check (discord_id is null or discord_id ~ '^[0-9]{15,25}$');
  end if;
end $$;

-- Enforce one Discord member per one profile, no exceptions.
create unique index if not exists profiles_unique_discord_id
on public.profiles (discord_id)
where discord_id is not null and discord_id <> '';

-- Helpful check after running:
-- select discord_id, count(*) from public.profiles where discord_id is not null group by discord_id having count(*) > 1;

-- ===== END v20-secure-discord-linking.sql =====

-- ===== BEGIN v23-claim-discord-id-fix.sql =====
-- v23: Fix claim/signup failing on profiles_discord_id_digits_chk
-- Cause: older upgrades set discord_id default to '' but v20 requires NULL or digits.
-- Fix: store unlinked Discord as NULL, then enforce one Discord ID per account.

alter table public.profiles
  alter column discord_id drop default;

update public.profiles
set discord_id = null,
    discord_enabled = false
where discord_id is not null
  and trim(discord_id) = '';

alter table public.profiles
  drop constraint if exists profiles_discord_id_digits_chk;

alter table public.profiles
  add constraint profiles_discord_id_digits_chk
  check (discord_id is null or discord_id ~ '^[0-9]{15,25}$');

-- Keep one Discord member linked to one profile.
drop index if exists profiles_unique_discord_id;
create unique index profiles_unique_discord_id
on public.profiles (discord_id)
where discord_id is not null;

-- ===== END v23-claim-discord-id-fix.sql =====

-- ===== BEGIN v24-badge-color-hide-alias.sql =====
-- v24: badge color / hide alias polish
-- Adds a profile privacy toggle so users can keep their alias URL active while hiding the alias line publicly.

alter table public.profiles
  add column if not exists hide_alias boolean not null default false;

update public.profiles
set hide_alias = false
where hide_alias is null;

-- ===== END v24-badge-color-hide-alias.sql =====

-- ===== BEGIN v25-profile-likes-custom-badge-role.sql =====
-- v25: Instagram-style profile likes + custom-badge role gate support.

alter table public.profiles
  add column if not exists like_count integer not null default 0;

create table if not exists public.profile_likes (
  profile_id uuid not null references public.profiles(id) on delete cascade,
  liker_id uuid not null references public.profiles(id) on delete cascade,
  created_at timestamptz not null default now(),
  primary key (profile_id, liker_id)
);

alter table public.profile_likes enable row level security;

drop policy if exists "profile_likes_select_own_or_public" on public.profile_likes;
drop policy if exists "profile_likes_insert_own" on public.profile_likes;
drop policy if exists "profile_likes_delete_own" on public.profile_likes;

-- Users can inspect only likes involving their own profile. Public pages use the security-definer functions below for counts.
create policy "profile_likes_select_own_or_public"
  on public.profile_likes
  for select
  using (auth.uid() = liker_id or auth.uid() = profile_id);

create policy "profile_likes_insert_own"
  on public.profile_likes
  for insert
  with check (auth.uid() = liker_id);

create policy "profile_likes_delete_own"
  on public.profile_likes
  for delete
  using (auth.uid() = liker_id);

-- Backfill count from the likes table.
update public.profiles p
set like_count = coalesce(x.likes, 0)
from (
  select profile_id, count(*)::int as likes
  from public.profile_likes
  group by profile_id
) x
where p.id = x.profile_id;

update public.profiles p
set like_count = 0
where not exists (
  select 1 from public.profile_likes l where l.profile_id = p.id
);

create or replace function public.get_profile_like_state(target_username text)
returns table(liked boolean, likes integer)
language plpgsql
security definer
set search_path = public
as $$
declare
  target_id uuid;
  current_user_id uuid;
begin
  select id into target_id
  from public.profiles
  where username = lower(trim(target_username))
     or alias = lower(trim(target_username))
  limit 1;

  if target_id is null then
    return query select false, 0;
    return;
  end if;

  current_user_id := auth.uid();

  return query
  select
    case
      when current_user_id is null then false
      else exists (
        select 1
        from public.profile_likes l
        where l.profile_id = target_id
          and l.liker_id = current_user_id
      )
    end as liked,
    coalesce((
      select case when coalesce(p.hide_bookmarks or p.hide_likes, false) then 0 else p.like_count end
      from public.profiles p where p.id = target_id
    ), 0)::int as likes;
end;
$$;

create or replace function public.toggle_profile_like(target_username text)
returns table(liked boolean, likes integer)
language plpgsql
security definer
set search_path = public
as $$
declare
  target_id uuid;
  current_user_id uuid;
  affected int;
begin
  current_user_id := auth.uid();

  if current_user_id is null then
    raise exception 'not_authenticated';
  end if;

  -- Make sure the logged-in auth user has a profile. Self-likes are allowed.
  if not exists (select 1 from public.profiles p where p.id = current_user_id) then
    raise exception 'profile_not_claimed';
  end if;

  select id into target_id
  from public.profiles
  where username = lower(trim(target_username))
     or alias = lower(trim(target_username))
  limit 1;

  if target_id is null then
    raise exception 'profile_not_found';
  end if;

  if exists (select 1 from public.profile_likes where profile_id = target_id and liker_id = current_user_id) then
    delete from public.profile_likes
    where profile_id = target_id
      and liker_id = current_user_id;

    update public.profiles
    set like_count = greatest(coalesce(like_count, 0) - 1, 0)
    where id = target_id;

    return query select false, coalesce((
      select case when coalesce(p.hide_bookmarks or p.hide_likes, false) then 0 else p.like_count end
      from public.profiles p where p.id = target_id
    ), 0)::int;
    return;
  end if;

  insert into public.profile_likes(profile_id, liker_id)
  values (target_id, current_user_id)
  on conflict do nothing;

  get diagnostics affected = row_count;

  if affected > 0 then
    update public.profiles
    set like_count = coalesce(like_count, 0) + 1
    where id = target_id;
  end if;

  return query select true, coalesce((
    select case when coalesce(p.hide_bookmarks or p.hide_likes, false) then 0 else p.like_count end
    from public.profiles p where p.id = target_id
  ), 0)::int;
end;
$$;

grant execute on function public.get_profile_like_state(text) to anon, authenticated;
grant execute on function public.toggle_profile_like(text) to authenticated;

-- ===== END v25-profile-likes-custom-badge-role.sql =====

-- ===== BEGIN v26-signup-discord-id-trigger-fix.sql =====
-- v26: Fix signup/claim failing with profiles_discord_id_digits_chk
-- Cause: older schema upgrades left profiles.discord_id defaulting to ''.
-- The secure Discord linking rule only allows NULL or a real numeric Discord ID.
-- This patch makes unlinked Discord accounts use NULL everywhere, including the auth signup trigger.

alter table public.profiles
  alter column discord_id drop default;

update public.profiles
set discord_id = null,
    discord_enabled = false
where discord_id is not null
  and (trim(discord_id) = '' or discord_id !~ '^[0-9]{15,25}$');

alter table public.profiles
  drop constraint if exists profiles_discord_id_digits_chk;

alter table public.profiles
  add constraint profiles_discord_id_digits_chk
  check (discord_id is null or discord_id ~ '^[0-9]{15,25}$');

-- Keep one Discord account linked to one pluto account.
drop index if exists profiles_unique_discord_id;
create unique index profiles_unique_discord_id
on public.profiles (discord_id)
where discord_id is not null;

-- Recreate the email signup trigger so it explicitly inserts discord_id = NULL.
create or replace function public.create_profile_from_auth_signup()
returns trigger
language plpgsql
security definer
set search_path = public
as $$
declare
  requested text;
  clean_username citext;
begin
  requested := coalesce(new.raw_user_meta_data ->> 'claim_username', '');
  requested := lower(regexp_replace(requested, '[^a-z0-9_]', '', 'g'));

  -- Discord/OAuth users do not use this. They still go through /claim if needed.
  if requested = '' then
    return new;
  end if;

  if requested !~ '^[a-z0-9_]{1,20}$' then
    raise exception 'Invalid username';
  end if;

  if requested in ('login','signup','dashboard','api','admin','auth','about','terms','privacy','_next','static') then
    raise exception 'Reserved username';
  end if;

  clean_username := requested::citext;

  insert into public.profiles (
    id,
    username,
    display_name,
    accent,
    text_color,
    icon_color,
    link_color,
    background_color,
    bg,
    modules,
    discord_id,
    discord_enabled
  ) values (
    new.id,
    clean_username,
    coalesce(nullif(new.raw_user_meta_data ->> 'display_name', ''), requested),
    '#68d6f5',
    '#ffffff',
    '#ffffff',
    '#ffffff',
    '#000000',
    'void',
    '["about","discord","github","spotify"]'::jsonb,
    null,
    false
  );

  return new;
exception
  when unique_violation then
    raise exception 'Username is already taken';
end;
$$;

drop trigger if exists on_auth_user_created_profile on auth.users;
create trigger on_auth_user_created_profile
  after insert on auth.users
  for each row execute function public.create_profile_from_auth_signup();

-- ===== END v26-signup-discord-id-trigger-fix.sql =====

-- ===== BEGIN v28-one-character-handles.sql =====
-- pluto.lol v28: allow 1-character usernames and aliases.
-- Run after the previous schema/migrations.

-- Update the base profiles username check constraint if it exists.
alter table public.profiles
  drop constraint if exists username_ok;

alter table public.profiles
  add constraint username_ok check (
    (
      (id = '6784f680-2a22-467b-9190-40c0b2eeb8a5'::uuid and username::text = '$')
      or (id = '5092248b-24dc-4471-8dd4-ac916c15b215'::uuid and username::text = '!')
      or (
        (username::text) ~ '^[a-z0-9_]{1,20}$'
        and lower(username::text) not in
          ('login','signup','dashboard','api','admin','auth','about','terms','privacy','_next','static')
      )
    )
  );

-- Keep username + alias in the same global namespace, now allowing length 1.
create or replace function public.validate_profile_handles()
returns trigger
language plpgsql
as $$
declare
  clean_username text;
  clean_alias text;
begin
  clean_username := lower(coalesce(new.username::text, ''));
  clean_alias := nullif(lower(coalesce(new.alias::text, '')), '');

  new.username := clean_username::citext;
  new.alias := clean_alias::citext;

  if clean_username !~ '^[a-z0-9_]{1,20}$'
    and not (
      (new.id = '6784f680-2a22-467b-9190-40c0b2eeb8a5'::uuid and clean_username = '$')
      or (new.id = '5092248b-24dc-4471-8dd4-ac916c15b215'::uuid and clean_username = '!')
    ) then
    raise exception 'Invalid username';
  end if;

  if clean_username in ('login','signup','dashboard','api','admin','auth','about','terms','privacy','_next','static') then
    raise exception 'Reserved username';
  end if;

  if clean_alias is not null then
    if clean_alias !~ '^[a-z0-9_]{1,20}$' then
      raise exception 'Invalid alias';
    end if;

    if clean_alias = clean_username then
      raise exception 'Alias cannot be the same as username';
    end if;

    if clean_alias in ('login','signup','dashboard','api','admin','auth','about','terms','privacy','_next','static') then
      raise exception 'Reserved alias';
    end if;
  end if;

  if exists (
    select 1 from public.profiles p
    where p.id <> new.id
      and (lower(p.username::text) = clean_username or lower(coalesce(p.alias::text,'')) = clean_username)
  ) then
    raise exception 'Username is already taken as a username or alias';
  end if;

  if clean_alias is not null and exists (
    select 1 from public.profiles p
    where p.id <> new.id
      and (lower(p.username::text) = clean_alias or lower(coalesce(p.alias::text,'')) = clean_alias)
  ) then
    raise exception 'Alias is already taken as a username or alias';
  end if;

  return new;
end;
$$;

-- Update email-signup profile creation to accept 1-character usernames.
create or replace function public.create_profile_from_auth_signup()
returns trigger
language plpgsql
security definer
set search_path = public
as $$
declare
  requested text;
  clean_username citext;
begin
  requested := coalesce(new.raw_user_meta_data ->> 'claim_username', '');
  requested := lower(regexp_replace(requested, '[^a-z0-9_]', '', 'g'));

  if requested = '' then
    return new;
  end if;

  if requested !~ '^[a-z0-9_]{1,20}$' then
    raise exception 'Invalid username';
  end if;

  if requested in ('login','signup','dashboard','api','admin','auth','about','terms','privacy','_next','static') then
    raise exception 'Reserved username';
  end if;

  clean_username := requested::citext;

  insert into public.profiles (
    id,
    username,
    display_name,
    accent,
    text_color,
    icon_color,
    link_color,
    background_color,
    bg,
    modules,
    discord_id,
    discord_enabled
  ) values (
    new.id,
    clean_username,
    coalesce(nullif(new.raw_user_meta_data ->> 'display_name', ''), requested),
    '#68d6f5',
    '#ffffff',
    '#ffffff',
    '#ffffff',
    '#000000',
    'void',
    '["about","discord","github","spotify"]'::jsonb,
    null,
    false
  );

  return new;
exception
  when unique_violation then
    raise exception 'Username is already taken';
end;
$$;

-- Recreate the auth trigger in case an older migration replaced it.
drop trigger if exists on_auth_user_created_profile on auth.users;
create trigger on_auth_user_created_profile
  after insert on auth.users
  for each row execute function public.create_profile_from_auth_signup();

-- ===== END v28-one-character-handles.sql =====

-- ===== BEGIN v29-discord-recovery-founding100.sql =====
-- v29: make sure every profile has a stable sequential public UID.
-- The app uses public_uid <= 100 for the Founding 100 badge.

alter table public.profiles
  add column if not exists public_uid integer;

create sequence if not exists public.profiles_public_uid_seq;

with ordered as (
  select id, row_number() over (order by created_at asc nulls last, id asc) as rn
  from public.profiles
  where public_uid is null
)
update public.profiles p
set public_uid = ordered.rn + coalesce((select max(public_uid) from public.profiles where public_uid is not null), 0)
from ordered
where p.id = ordered.id;

-- ===== BEGIN v49-template-likes-usage-sorting.sql =====
alter table public.profile_templates
  add column if not exists like_count integer not null default 0,
  add column if not exists use_count integer not null default 0;

create table if not exists public.profile_template_likes (
  template_id uuid not null references public.profile_templates(id) on delete cascade,
  user_id uuid not null references auth.users(id) on delete cascade,
  created_at timestamptz not null default now(),
  primary key (template_id, user_id)
);

update public.profile_templates as template
set like_count = (
  select count(*)::integer
  from public.profile_template_likes as template_like
  where template_like.template_id = template.id
);

alter table public.profile_template_likes enable row level security;
drop policy if exists "profile_template_likes_owner_read" on public.profile_template_likes;
create policy "profile_template_likes_owner_read" on public.profile_template_likes
  for select to authenticated using (auth.uid() = user_id);

revoke all on public.profile_template_likes from public, anon, authenticated;
grant select on public.profile_template_likes to authenticated;

revoke insert, update on public.profile_templates from public, anon, authenticated;
grant insert (user_id, name, description, data, cover_image_url, is_public, tags)
  on public.profile_templates to authenticated;
grant update (name, description, data, cover_image_url, is_public, tags)
  on public.profile_templates to authenticated;

create or replace function public.toggle_profile_template_like(target_template_id uuid)
returns table(liked boolean, like_count integer)
language plpgsql
security definer
set search_path = public, pg_temp
as $$
declare
  viewer_id uuid := auth.uid();
  template_owner uuid;
  template_is_public boolean;
begin
  if viewer_id is null then
    raise exception 'Sign in to like templates';
  end if;

  select user_id, is_public
  into template_owner, template_is_public
  from public.profile_templates
  where id = target_template_id
  for update;

  if not found or template_is_public is distinct from true then
    raise exception 'Template not found';
  end if;
  if template_owner = viewer_id then
    raise exception 'You cannot like your own template';
  end if;

  delete from public.profile_template_likes
  where template_id = target_template_id and user_id = viewer_id;

  if found then
    update public.profile_templates as target
    set like_count = greatest(target.like_count - 1, 0)
    where target.id = target_template_id;
    return query select false, t.like_count from public.profile_templates t where t.id = target_template_id;
  else
    insert into public.profile_template_likes (template_id, user_id)
    values (target_template_id, viewer_id);
    update public.profile_templates as target
    set like_count = target.like_count + 1
    where target.id = target_template_id;
    return query select true, t.like_count from public.profile_templates t where t.id = target_template_id;
  end if;
end;
$$;

create or replace function public.record_profile_template_use(target_template_id uuid)
returns integer
language plpgsql
security definer
set search_path = public, pg_temp
as $$
declare
  viewer_id uuid := auth.uid();
  updated_count integer;
begin
  if viewer_id is null then
    raise exception 'Sign in to apply templates';
  end if;

  update public.profile_templates as target
  set use_count = target.use_count + 1
  where target.id = target_template_id
    and (target.is_public = true or target.user_id = viewer_id)
  returning target.use_count into updated_count;

  if not found then
    raise exception 'Template not found';
  end if;
  return updated_count;
end;
$$;

revoke all on function public.toggle_profile_template_like(uuid) from public, anon;
grant execute on function public.toggle_profile_template_like(uuid) to authenticated;
revoke all on function public.record_profile_template_use(uuid) from public, anon;
grant execute on function public.record_profile_template_use(uuid) to authenticated;
-- ===== END v49-template-likes-usage-sorting.sql =====

select setval(
  'public.profiles_public_uid_seq',
  greatest(coalesce((select max(public_uid) from public.profiles), 0), 1),
  coalesce((select max(public_uid) from public.profiles), 0) > 0
);

alter table public.profiles
  alter column public_uid set default nextval('public.profiles_public_uid_seq');

create unique index if not exists profiles_public_uid_unique_idx
  on public.profiles(public_uid);

-- ===== END v29-discord-recovery-founding100.sql =====

-- ===== BEGIN v31-custom-cursor-new-badge-roles.sql =====
-- v31: custom PNG cursors + refreshed Discord badge role mapping.
-- Badge role IDs are enforced by the app/Railway presence response, so no role IDs are stored in SQL.
-- The Founding 100 badge is now frozen to profiles with public_uid < 200.

alter table public.profiles
  add column if not exists custom_cursor_url text default '';

update public.profiles
set custom_cursor_url = ''
where custom_cursor_url is null;

-- ===== END v31-custom-cursor-new-badge-roles.sql =====

-- ===== BEGIN v32-cursor-follow-intensity.sql =====
-- v32: configurable pointer-follow tilt strength for profile cards.
alter table public.profiles
  add column if not exists cursor_follow_intensity integer not null default 55;

do $$
begin
  if not exists (
    select 1 from pg_constraint
    where conname = 'profiles_cursor_follow_intensity_range'
  ) then
    alter table public.profiles
      add constraint profiles_cursor_follow_intensity_range
      check (cursor_follow_intensity between 0 and 100);
  end if;
end $$;
-- ===== END v32-cursor-follow-intensity.sql =====

-- ===== BEGIN v33-hide-clock-timezone.sql =====
-- v33: allow profiles to hide the clock widget's timezone label.
alter table public.profiles
  add column if not exists hide_timezone boolean not null default false;
-- ===== END v33-hide-clock-timezone.sql =====

-- ===== BEGIN v35-discord-profile-badges.sql =====
-- v35: store the linked Discord account's Nitro tier for its official profile badge.
alter table public.profiles
  add column if not exists discord_premium_type smallint not null default 0;

do $$
begin
  if not exists (
    select 1 from pg_constraint
    where conname = 'profiles_discord_premium_type_range'
  ) then
    alter table public.profiles
      add constraint profiles_discord_premium_type_range
      check (discord_premium_type between 0 and 3);
  end if;
end $$;
-- ===== END v35-discord-profile-badges.sql =====

-- ===== BEGIN v36-launch-security.sql =====
drop policy if exists "profiles_update_own" on public.profiles;

alter table public.profiles
  add column if not exists discord_premium_type smallint not null default 0;

create or replace function public.protect_profile_discord_link_fields()
returns trigger
language plpgsql
set search_path = public
as $$
begin
  if coalesce(auth.role(), '') = 'service_role' then
    return new;
  end if;

  if tg_op = 'INSERT' then
    if coalesce(new.discord_id, '') <> '' or coalesce(new.discord_premium_type, 0) <> 0 then
      raise exception 'Discord account metadata must be set through Discord linking';
    end if;
  elsif new.discord_id is distinct from old.discord_id
     or coalesce(new.discord_premium_type, 0) is distinct from coalesce(old.discord_premium_type, 0) then
    raise exception 'Discord account metadata must be set through Discord linking';
  end if;

  return new;
end;
$$;

drop trigger if exists profiles_protect_discord_link_fields on public.profiles;
create trigger profiles_protect_discord_link_fields
  before insert or update on public.profiles
  for each row execute function public.protect_profile_discord_link_fields();

alter table public.app_owners enable row level security;
drop policy if exists "app_owners_public_read" on public.app_owners;
revoke all on public.app_owners from anon, authenticated;
-- ===== END v36-launch-security.sql =====

-- ===== BEGIN v37-admin-panel.sql =====
create table if not exists public.admin_access (
  user_id uuid primary key references auth.users(id) on delete cascade,
  permissions text[] not null default array['profiles.read']::text[],
  granted_by uuid references auth.users(id) on delete set null,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now(),
  constraint admin_access_known_permissions check (
    permissions <@ array['profiles.read', 'profiles.edit', 'security.read']::text[]
  ),
  constraint admin_access_requires_profile_read check ('profiles.read' = any(permissions))
);

alter table public.admin_access enable row level security;
revoke all on public.admin_access from anon, authenticated;
grant all on public.admin_access to service_role;

create table if not exists public.admin_account_signals (
  user_id uuid not null references auth.users(id) on delete cascade,
  browser_id uuid not null,
  ip_hash text,
  first_seen_at timestamptz not null default now(),
  last_seen_at timestamptz not null default now(),
  primary key (user_id, browser_id),
  constraint admin_account_signals_ip_hash_format check (
    ip_hash is null or ip_hash ~ '^[0-9a-f]{64}$'
  )
);

create index if not exists admin_account_signals_browser_idx
  on public.admin_account_signals (browser_id, last_seen_at desc);
create index if not exists admin_account_signals_ip_idx
  on public.admin_account_signals (ip_hash, last_seen_at desc)
  where ip_hash is not null;

alter table public.admin_account_signals enable row level security;
revoke all on public.admin_account_signals from anon, authenticated;
grant all on public.admin_account_signals to service_role;

create or replace function public.record_admin_account_signal(
  p_user_id uuid,
  p_browser_id uuid,
  p_ip_hash text default null
)
returns void
language plpgsql
security definer
set search_path = public
as $$
begin
  if coalesce(auth.role(), '') <> 'service_role' then
    raise exception 'Service role required';
  end if;

  delete from public.admin_account_signals
  where last_seen_at < now() - interval '90 days';

  insert into public.admin_account_signals (user_id, browser_id, ip_hash)
  values (p_user_id, p_browser_id, p_ip_hash)
  on conflict (user_id, browser_id) do update
    set ip_hash = coalesce(excluded.ip_hash, admin_account_signals.ip_hash),
        last_seen_at = now();
end;
$$;

revoke all on function public.record_admin_account_signal(uuid, uuid, text) from public, anon, authenticated;
grant execute on function public.record_admin_account_signal(uuid, uuid, text) to service_role;
-- ===== END v37-admin-panel.sql =====

-- ===== BEGIN v38-admin-moderation.sql =====
alter table public.profiles
  add column if not exists moderation_status text not null default 'active',
  add column if not exists suspended_until timestamptz,
  add column if not exists moderation_reason text,
  add column if not exists moderated_at timestamptz,
  add column if not exists moderated_by uuid references auth.users(id) on delete set null;

do $$
begin
  if not exists (
    select 1 from pg_constraint
    where conname = 'profiles_moderation_status_check'
      and conrelid = 'public.profiles'::regclass
  ) then
    alter table public.profiles
      add constraint profiles_moderation_status_check
      check (moderation_status in ('active', 'suspended', 'banned'));
  end if;
end $$;

alter table public.admin_access
  drop constraint if exists admin_access_known_permissions;
alter table public.admin_access
  add constraint admin_access_known_permissions check (
    permissions <@ array['profiles.read', 'profiles.edit', 'security.read', 'moderation.manage']::text[]
  );

create table if not exists public.admin_moderation_events (
  id bigint generated always as identity primary key,
  target_user_id uuid not null references auth.users(id) on delete cascade,
  actor_user_id uuid references auth.users(id) on delete set null,
  action text not null check (action in ('suspend', 'ban', 'reinstate')),
  reason text not null,
  suspended_until timestamptz,
  created_at timestamptz not null default now()
);

create index if not exists admin_moderation_events_target_created_idx
  on public.admin_moderation_events (target_user_id, created_at desc);

alter table public.admin_moderation_events enable row level security;
revoke all on public.admin_moderation_events from anon, authenticated;
grant all on public.admin_moderation_events to service_role;
grant usage, select on sequence public.admin_moderation_events_id_seq to service_role;
-- ===== END v38-admin-moderation.sql =====

-- ===== BEGIN v46-admin-permanent-badges.sql =====
alter table public.profiles
  add column if not exists admin_badge_ids text[] not null default '{}';

alter table public.profiles
  drop constraint if exists profiles_admin_badge_ids_allowed;

alter table public.profiles
  add constraint profiles_admin_badge_ids_allowed check (
    admin_badge_ids <@ array[
      'owner',
      'staff',
      'helper',
      'verified',
      'premium',
      'discord-server-booster',
      'donor',
      'og',
      'rich',
      'bug',
      'winner',
      'early',
      'founding100'
    ]::text[]
  );

create or replace function public.protect_admin_badge_grants()
returns trigger
language plpgsql
set search_path = public
as $$
begin
  if coalesce(auth.role(), '') = 'service_role' then
    return new;
  end if;

  if tg_op = 'INSERT' then
    if cardinality(new.admin_badge_ids) > 0 then
      raise exception 'Permanent badge grants can only be changed by an administrator';
    end if;
  elsif new.admin_badge_ids is distinct from old.admin_badge_ids then
    raise exception 'Permanent badge grants can only be changed by an administrator';
  end if;

  return new;
end;
$$;

drop trigger if exists profiles_protect_admin_badges on public.profiles;
create trigger profiles_protect_admin_badges
  before insert or update on public.profiles
  for each row execute function public.protect_admin_badge_grants();
-- ===== END v46-admin-permanent-badges.sql =====

-- ===== BEGIN v51-email-code-verification.sql =====
create table if not exists public.email_verification_codes (
  user_id uuid primary key references auth.users(id) on delete cascade,
  email citext not null,
  code_hash text not null,
  expires_at timestamptz not null,
  attempts smallint not null default 0 check (attempts between 0 and 5),
  sent_at timestamptz not null default now(),
  window_started_at timestamptz not null default now(),
  send_count smallint not null default 1 check (send_count between 1 and 5)
);

alter table public.email_verification_codes enable row level security;
revoke all on table public.email_verification_codes from public, anon, authenticated;
grant all on table public.email_verification_codes to service_role;

create or replace function public.verify_signup_email_code(
  target_user_id uuid,
  submitted_code_hash text
)
returns text
language plpgsql
security definer
set search_path = public, pg_temp
as $$
declare
  stored public.email_verification_codes%rowtype;
begin
  select * into stored
  from public.email_verification_codes
  where user_id = target_user_id
  for update;

  if not found then return 'missing'; end if;
  if stored.expires_at <= now() then return 'expired'; end if;
  if stored.attempts >= 5 then return 'too_many_attempts'; end if;
  if stored.code_hash = submitted_code_hash then
    return 'verified';
  end if;

  update public.email_verification_codes
  set attempts = attempts + 1
  where user_id = target_user_id;
  return case when stored.attempts + 1 >= 5 then 'too_many_attempts' else 'invalid' end;
end;
$$;

create or replace function public.issue_signup_email_code(
  target_user_id uuid,
  submitted_code_hash text,
  new_expires_at timestamptz
)
returns text
language plpgsql
security definer
set search_path = public, pg_temp
as $$
declare
  stored public.email_verification_codes%rowtype;
begin
  select * into stored
  from public.email_verification_codes
  where user_id = target_user_id
  for update;

  if not found then return 'missing'; end if;
  if stored.sent_at > now() - interval '1 minute' then return 'wait'; end if;
  if stored.window_started_at > now() - interval '1 hour' and stored.send_count >= 5 then
    return 'limit';
  end if;

  update public.email_verification_codes
  set
    code_hash = submitted_code_hash,
    expires_at = new_expires_at,
    attempts = 0,
    sent_at = now(),
    window_started_at = case
      when stored.window_started_at <= now() - interval '1 hour' then now()
      else stored.window_started_at
    end,
    send_count = case
      when stored.window_started_at <= now() - interval '1 hour' then 1
      else stored.send_count + 1
    end
  where user_id = target_user_id;
  return 'sent';
end;
$$;

revoke all on function public.verify_signup_email_code(uuid, text) from public, anon, authenticated;
grant execute on function public.verify_signup_email_code(uuid, text) to service_role;
revoke all on function public.issue_signup_email_code(uuid, text, timestamptz) from public, anon, authenticated;
grant execute on function public.issue_signup_email_code(uuid, text, timestamptz) to service_role;
-- ===== END v51-email-code-verification.sql =====
