-- Migration: v82-discord-activity-levels.sql
-- Description: Message & Voice Chat (VC) activity leveling and leaderboard tracking for Discord

create table if not exists public.discord_activity_levels (
  discord_id text primary key,
  guild_id text not null default '1510717707409166497',
  xp bigint not null default 0,
  level integer not null default 0,
  message_count integer not null default 0,
  voice_seconds bigint not null default 0,
  last_message_at timestamptz,
  last_voice_at timestamptz,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

-- Performance indexes for leaderboard ranking
create index if not exists idx_discord_levels_xp on public.discord_activity_levels (xp desc);
create index if not exists idx_discord_levels_msg on public.discord_activity_levels (message_count desc);
create index if not exists idx_discord_levels_vc on public.discord_activity_levels (voice_seconds desc);

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

-- Revoke direct writes from anon/authenticated so all awards go through verified service_role / bot
revoke all on public.discord_activity_levels from anon, authenticated;
grant select on public.discord_activity_levels to anon, authenticated;
grant all on public.discord_activity_levels to service_role;

drop policy if exists "Allow public select on discord_activity_levels" on public.discord_activity_levels;
create policy "Allow public select on discord_activity_levels"
  on public.discord_activity_levels
  for select
  to anon, authenticated
  using (true);

drop policy if exists "Allow service_role full access on discord_activity_levels" on public.discord_activity_levels;
create policy "Allow service_role full access on discord_activity_levels"
  on public.discord_activity_levels
  for all
  to service_role
  using (true)
  with check (true);

-- Atomic RPC for recording message & voice activity and calculating level-ups
create or replace function public.record_discord_activity(
  p_discord_id text,
  p_guild_id text default '1510717707409166497',
  p_xp_gain integer default 0,
  p_msg_gain integer default 0,
  p_voice_gain integer default 0
) returns jsonb language plpgsql security definer as $$
declare
  v_rec record;
  v_old_level integer;
  v_new_level integer;
  v_new_xp bigint;
  v_calc_level integer := 0;
begin
  insert into public.discord_activity_levels (discord_id, guild_id, xp, level, message_count, voice_seconds, last_message_at, last_voice_at, updated_at)
  values (
    p_discord_id,
    p_guild_id,
    p_xp_gain,
    0,
    p_msg_gain,
    p_voice_gain,
    case when p_msg_gain > 0 then now() else null end,
    case when p_voice_gain > 0 then now() else null end,
    now()
  )
  on conflict (discord_id) do update set
    xp = discord_activity_levels.xp + excluded.xp,
    message_count = discord_activity_levels.message_count + excluded.message_count,
    voice_seconds = discord_activity_levels.voice_seconds + excluded.voice_seconds,
    last_message_at = coalesce(excluded.last_message_at, discord_activity_levels.last_message_at),
    last_voice_at = coalesce(excluded.last_voice_at, discord_activity_levels.last_voice_at),
    updated_at = now()
  returning * into v_rec;

  v_old_level := v_rec.level;
  v_new_xp := v_rec.xp;

  -- Compute new level: 25 * L^2 + 75 * L <= xp
  while (25 * (v_calc_level + 1) * (v_calc_level + 1) + 75 * (v_calc_level + 1)) <= v_new_xp loop
    v_calc_level := v_calc_level + 1;
  end loop;

  v_new_level := v_calc_level;

  if v_new_level <> v_old_level then
    update public.discord_activity_levels
    set level = v_new_level
    where discord_id = p_discord_id;
  end if;

  return jsonb_build_object(
    'discord_id', p_discord_id,
    'xp', v_new_xp,
    'old_level', v_old_level,
    'new_level', v_new_level,
    'leveled_up', (v_new_level > v_old_level),
    'message_count', v_rec.message_count,
    'voice_seconds', v_rec.voice_seconds
  );
end;
$$;

revoke all on function public.record_discord_activity from public, anon, authenticated;
grant execute on function public.record_discord_activity to service_role;

-- Function to get a user's calculated rank and activity stats
create or replace function public.get_discord_user_rank(
  p_discord_id text
) returns jsonb language plpgsql security definer as $$
declare
  v_rec record;
  v_rank bigint;
  v_total bigint;
begin
  select * into v_rec from public.discord_activity_levels where discord_id = p_discord_id;
  if not found then
    return null;
  end if;

  select count(*) + 1 into v_rank from public.discord_activity_levels where xp > v_rec.xp;
  select count(*) into v_total from public.discord_activity_levels;

  return jsonb_build_object(
    'discord_id', v_rec.discord_id,
    'xp', v_rec.xp,
    'level', v_rec.level,
    'rank', v_rank,
    'total_ranked', v_total,
    'message_count', v_rec.message_count,
    'voice_seconds', v_rec.voice_seconds
  );
end;
$$;

revoke all on function public.get_discord_user_rank from public, anon, authenticated;
grant execute on function public.get_discord_user_rank to service_role;
