-- ==============================================================================
-- v71: Promoter Role & 1.5x Daily Reward Multiplier
-- ==============================================================================

-- 1. Add promoter columns to public.profiles
alter table public.profiles
  add column if not exists is_promoter boolean not null default false,
  add column if not exists promoter_verified_at timestamptz default null;

create index if not exists idx_profiles_is_promoter on public.profiles(is_promoter)
  where is_promoter is true;

alter table if exists public.global_chat_messages
  add column if not exists is_promoter boolean not null default false;

-- 2. Secure helper RPC to update promoter status from Discord bot or server actions
create or replace function public.set_promoter_status(
  p_discord_id text,
  p_is_promoter boolean
)
returns jsonb
language plpgsql
security definer
set search_path = public
as $$
declare
  v_updated_count integer;
begin
  if p_discord_id is null or trim(p_discord_id) = '' then
    return jsonb_build_object('success', false, 'error', 'Invalid discord_id');
  end if;

  update public.profiles
  set
    is_promoter = p_is_promoter,
    promoter_verified_at = case when p_is_promoter then clock_timestamp() else null end
  where discord_id = p_discord_id;

  get diagnostics v_updated_count = row_count;

  return jsonb_build_object(
    'success', true,
    'discord_id', p_discord_id,
    'is_promoter', p_is_promoter,
    'profiles_updated', v_updated_count
  );
end;
$$;

revoke all on function public.set_promoter_status(text, boolean) from public, anon, authenticated;
grant execute on function public.set_promoter_status(text, boolean) to service_role;

-- 3. Update public.claim_daily_reward to apply 1.5x credit multiplier for promoters
create or replace function public.claim_daily_reward(
  p_user_id uuid
)
returns jsonb
language plpgsql
security definer
set search_path = public
as $$
declare
  v_profile record;
  v_now timestamptz := clock_timestamp();
  v_diff_seconds numeric;
  v_new_streak integer;
  v_credits_to_grant integer;
  v_premium_hours integer;
  v_new_credits integer;
  v_current_premium timestamptz;
  v_new_premium timestamptz;
  v_is_promoter boolean := false;
begin
  -- Lock user profile row
  select id, credits, daily_streak, last_daily_claim_at, premium_until, admin_badge_ids, coalesce(is_promoter, false) as is_promoter
  into v_profile
  from public.profiles
  where id = p_user_id
  for update;

  if not found then
    return jsonb_build_object('success', false, 'error', 'Profile not found');
  end if;

  v_is_promoter := coalesce(v_profile.is_promoter, false);

  -- 1. Check cooldown on this account
  if v_profile.last_daily_claim_at is not null then
    v_diff_seconds := extract(epoch from (v_now - v_profile.last_daily_claim_at));
    if v_diff_seconds < 72000 then
      return jsonb_build_object(
        'success', false,
        'error', 'Daily reward already claimed today.',
        'seconds_remaining', ceil(72000 - v_diff_seconds)
      );
    end if;

    -- If more than 48 hours (172,800 seconds), streak has lapsed -> reset to day 1
    if v_diff_seconds > 172800 then
      v_new_streak := 1;
    else
      -- Increment streak, cycling back after day 7
      v_new_streak := (v_profile.daily_streak % 7) + 1;
    end if;
  else
    v_new_streak := 1;
  end if;

  -- 2. Check if any related/linked account claimed within the 20h cooldown
  if exists (
    select 1
    from public.profiles p2
    where p2.id <> p_user_id
      and p2.last_daily_claim_at is not null
      and extract(epoch from (v_now - p2.last_daily_claim_at)) < 72000
      and public.are_accounts_related(p_user_id, p2.id)
  ) then
    return jsonb_build_object(
      'success', false,
      'error', 'Daily reward already claimed today on another account linked to your device or network. Free rewards can only be claimed on one account per day. You can transfer credits between your linked accounts.',
      'seconds_remaining', 72000
    );
  end if;

  -- Determine rewards based on streak day
  case v_new_streak
    when 1 then
      v_credits_to_grant := 50;
      v_premium_hours := 0;
    when 2 then
      v_credits_to_grant := 75;
      v_premium_hours := 0;
    when 3 then
      v_credits_to_grant := 100;
      v_premium_hours := 12;
    when 4 then
      v_credits_to_grant := 125;
      v_premium_hours := 0;
    when 5 then
      v_credits_to_grant := 175;
      v_premium_hours := 0;
    when 6 then
      v_credits_to_grant := 250;
      v_premium_hours := 0;
    when 7 then
      v_credits_to_grant := 500;
      v_premium_hours := 24;
    else
      v_credits_to_grant := 50;
      v_premium_hours := 0;
  end case;

  -- Apply 1.5x Promoter multiplier
  if v_is_promoter then
    v_credits_to_grant := round(v_credits_to_grant * 1.5);
  end if;

  v_new_credits := coalesce(v_profile.credits, 0) + v_credits_to_grant;

  -- Calculate premium extension if day grants premium hours
  v_current_premium := v_profile.premium_until;
  if v_premium_hours > 0 then
    if v_current_premium is not null and v_current_premium > v_now then
      v_new_premium := v_current_premium + (v_premium_hours || ' hours')::interval;
    else
      v_new_premium := v_now + (v_premium_hours || ' hours')::interval;
    end if;
  else
    v_new_premium := v_current_premium;
  end if;

  -- Update profile streak, timestamp, credits, and premium
  update public.profiles
  set
    credits = v_new_credits,
    daily_streak = v_new_streak,
    last_daily_claim_at = v_now,
    premium_until = v_new_premium
  where id = p_user_id;

  -- Log credit transaction
  insert into public.credit_transactions (
    user_id,
    amount,
    balance_after,
    action,
    description,
    metadata
  ) values (
    p_user_id,
    v_credits_to_grant,
    v_new_credits,
    'daily_reward',
    'Claimed Day ' || v_new_streak || ' Daily Reward (+' || v_credits_to_grant || ' credits' || case when v_is_promoter then ' · 1.5x Promoter Boost' else '' end || ')',
    jsonb_build_object(
      'streak', v_new_streak,
      'premium_hours_granted', v_premium_hours,
      'is_promoter', v_is_promoter,
      'promoter_multiplier', case when v_is_promoter then 1.5 else 1.0 end
    )
  );

  return jsonb_build_object(
    'success', true,
    'streak', v_new_streak,
    'credits_granted', v_credits_to_grant,
    'premium_hours_granted', v_premium_hours,
    'new_credits', v_new_credits,
    'is_promoter', v_is_promoter,
    'multiplier', case when v_is_promoter then 1.5 else 1.0 end
  );
end;
$$;

revoke all on function public.claim_daily_reward(uuid) from public, anon, authenticated;
grant execute on function public.claim_daily_reward(uuid) to service_role;
