-- ---------------------------------------------------------------
-- 021 — partner attribution (A1 Session 3, per docs/PARTNERS.md).
--
-- Adds user_profiles.partner_ref (the external partner code captured from
-- the ?ref= cookie at signup and stored in auth metadata), extends
-- handle_new_user to copy it on profile creation (verified against the
-- LIVE function definition — it inserts (id, email) only; this adds one
-- column and preserves SECURITY DEFINER + search_path), and backfills
-- rows whose auth metadata already carries a ref.
--
-- Distinct from migration 004's USER-referral system: partner codes are
-- external strings; no dependency on referral_codes tables.
-- ---------------------------------------------------------------

ALTER TABLE public.user_profiles
  ADD COLUMN IF NOT EXISTS partner_ref text;

CREATE INDEX IF NOT EXISTS idx_user_profiles_partner_ref
  ON public.user_profiles(partner_ref)
  WHERE partner_ref IS NOT NULL;

CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $function$
begin
  insert into public.user_profiles (id, email, partner_ref)
  values (
    new.id,
    new.email,
    upper(nullif(new.raw_user_meta_data->>'partner_ref', ''))
  )
  on conflict (id) do nothing;
  return new;
end;
$function$;

-- One-time backfill for signups that predate the column.
UPDATE public.user_profiles p
SET partner_ref = upper(u.raw_user_meta_data->>'partner_ref')
FROM auth.users u
WHERE u.id = p.id
  AND p.partner_ref IS NULL
  AND nullif(u.raw_user_meta_data->>'partner_ref', '') IS NOT NULL;
