-- v56: Comments, pin comments, about me, link clicks, embed presets,
-- referrals, onboarding, viewer theme, view-log for leaderboard periods.

-- Profile-level feature columns
alter table public.profiles add column if not exists comments_enabled boolean default true;
alter table public.profiles add column if not exists pinned_comment_id uuid;
alter table public.profiles add column if not exists about_me text default '';
alter table public.profiles add column if not exists scroll_enabled boolean default false;
alter table public.profiles add column if not exists embed_preset text default 'classic';
alter table public.profiles add column if not exists referral_code text;
alter table public.profiles add column if not exists link_clicks jsonb default '{}'::jsonb;
alter table public.profiles add column if not exists tos_accepted_at timestamptz;
alter table public.profiles add column if not exists onboarding_dismissed boolean default false;
alter table public.profiles add column if not exists premium_until timestamptz;
create unique index if not exists profiles_referral_code_key on public.profiles(referral_code) where referral_code is not null;

-- Comments
create table if not exists public.profile_comments (
  id uuid primary key default gen_random_uuid(),
  profile_id uuid not null references public.profiles(id) on delete cascade,
  author_id uuid references auth.users(id) on delete set null,
  author_username text not null default 'anonymous',
  author_avatar_url text default '',
  content text not null,
  created_at timestamptz not null default now()
);
alter table public.profile_comments enable row level security;
drop policy if exists "profile_comments_no_direct" on public.profile_comments;
create policy "profile_comments_no_direct" on public.profile_comments for select using (false);
create index if not exists profile_comments_profile_idx on public.profile_comments(profile_id, created_at desc);

alter table public.profiles
  drop constraint if exists profiles_pinned_comment_fk,
  add constraint profiles_pinned_comment_fk foreign key (pinned_comment_id) references public.profile_comments(id) on delete set null;

-- Referrals
create table if not exists public.referrals (
  id uuid primary key default gen_random_uuid(),
  referrer_id uuid not null references public.profiles(id) on delete cascade,
  referred_id uuid not null references public.profiles(id) on delete cascade,
  ip_hash text default '',
  user_agent_hash text default '',
  status text not null default 'valid' check (status in ('valid','flagged')),
  rewarded boolean not null default false,
  created_at timestamptz not null default now(),
  unique (referred_id)
);
alter table public.referrals enable row level security;
drop policy if exists "referrals_no_direct" on public.referrals;
create policy "referrals_no_direct" on public.referrals for select using (false);
create index if not exists referrals_referrer_idx on public.referrals(referrer_id);

create table if not exists public.referral_rewards (
  id uuid primary key default gen_random_uuid(),
  profile_id uuid not null references public.profiles(id) on delete cascade,
  kind text not null default 'premium_days',
  days integer not null default 7,
  valid_referrals_at_grant integer not null,
  granted_at timestamptz not null default now(),
  expires_at timestamptz,
  claimed boolean not null default false,
  unique (profile_id, valid_referrals_at_grant)
);
alter table public.referral_rewards enable row level security;
drop policy if exists "referral_rewards_no_direct" on public.referral_rewards;
create policy "referral_rewards_no_direct" on public.referral_rewards for select using (false);

-- View log for leaderboard period queries (append-only, per unique view)
create table if not exists public.profile_view_log (
  id bigint generated always as identity primary key,
  profile_id uuid not null references public.profiles(id) on delete cascade,
  created_at timestamptz not null default now()
);
alter table public.profile_view_log enable row level security;
drop policy if exists "profile_view_log_no_direct" on public.profile_view_log;
create policy "profile_view_log_no_direct" on public.profile_view_log for select using (false);
create index if not exists profile_view_log_period_idx on public.profile_view_log(profile_id, created_at desc);

-- Rewrite increment_view_once to also record into profile_view_log
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;
    insert into public.profile_view_log(profile_id) values (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;

-- Leaderboard by period
create or replace function public.leaderboard_by_period(period_start timestamptz, result_limit integer default 50)
returns table (profile_id uuid, view_count bigint)
language sql
security definer
set search_path = public
stable
as $$
  select profile_id, count(*) as view_count
  from public.profile_view_log
  where created_at >= period_start
  group by profile_id
  order by view_count desc
  limit result_limit;
$$;
revoke all on function public.leaderboard_by_period(timestamptz, integer) from public, anon, authenticated;
grant execute on function public.leaderboard_by_period(timestamptz, integer) to service_role;

-- Link click increment
create or replace function public.increment_link_click(profile_username citext, link_url 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 or link_url is null or length(link_url) > 500 then
    return;
  end if;
  update public.profiles
  set link_clicks = jsonb_set(
    coalesce(link_clicks, '{}'::jsonb),
    array[link_url],
    to_jsonb(coalesce((link_clicks ->> link_url)::int, 0) + 1),
    true
  )
  where id = target_id;
end;
$$;
revoke all on function public.increment_link_click(citext, text) from public, anon, authenticated;
grant execute on function public.increment_link_click(citext, text) to service_role;
