-- ============================================================================
-- Migration: v63-daily-rewards.sql
-- Daily login rewards granting Sinss Credits, Premium trial access, and badges.
-- ============================================================================

-- 1. Add streak tracking to profiles
alter table public.profiles
  add column if not exists daily_streak integer not null default 0 check (daily_streak >= 0);

alter table public.profiles
  add column if not exists last_daily_claim_at timestamptz default null;

-- 2. Daily Rewards Claims Audit Table
create table if not exists public.daily_reward_claims (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users(id) on delete cascade,
  day_number integer not null check (day_number between 1 and 7),
  credits_granted integer not null default 0,
  premium_hours_granted integer not null default 0,
  claimed_at timestamptz not null default now(),
  metadata jsonb default '{}'::jsonb
);

create index if not exists idx_daily_reward_claims_user
  on public.daily_reward_claims(user_id, claimed_at desc);

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

drop policy if exists "Users can read own daily reward claims" on public.daily_reward_claims;
create policy "Users can read own daily reward claims"
  on public.daily_reward_claims for select
  using (auth.uid() = user_id);

-- 4. Atomic Daily Reward Claim RPC Function
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;
begin
  -- Lock user profile row
  select id, credits, daily_streak, last_daily_claim_at, premium_until, admin_badge_ids
  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;

  -- Check cooldown: must be at least 20 hours (72,000 seconds) since last claim
  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;

  -- 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;

  -- 1. Calculate new credits
  v_new_credits := coalesce(v_profile.credits, 0) + v_credits_to_grant;

  -- 2. Calculate new premium_until if premium trial granted
  v_new_premium := v_profile.premium_until;
  if v_premium_hours > 0 then
    if v_profile.premium_until is not null and v_profile.premium_until > v_now then
      v_new_premium := v_profile.premium_until + (v_premium_hours || ' hours')::interval;
    else
      v_new_premium := v_now + (v_premium_hours || ' hours')::interval;
    end if;
  end if;

  -- 3. Update profile
  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;

  -- 4. Record credit transaction
  if v_credits_to_grant > 0 then
    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_day_' || v_new_streak,
      'Claimed Day ' || v_new_streak || ' Daily Login Reward',
      jsonb_build_object(
        'day', v_new_streak,
        'premium_hours', v_premium_hours
      )
    );
  end if;

  -- 5. Record daily claim audit
  insert into public.daily_reward_claims (
    user_id,
    day_number,
    credits_granted,
    premium_hours_granted,
    claimed_at,
    metadata
  ) values (
    p_user_id,
    v_new_streak,
    v_credits_to_grant,
    v_premium_hours,
    v_now,
    jsonb_build_object('streak', v_new_streak)
  );

  return jsonb_build_object(
    'success', true,
    'day', v_new_streak,
    'credits_granted', v_credits_to_grant,
    'premium_hours_granted', v_premium_hours,
    'new_balance', v_new_credits,
    'new_premium_until', v_new_premium,
    'claimed_at', v_now
  );
end;
$$;

-- Permissions
revoke all on function public.claim_daily_reward(uuid) from public;
grant execute on function public.claim_daily_reward(uuid) to authenticated, service_role;
