-- 0001_initial.sql — users + subscriptions tables, with RLS examples.
--
-- Apply via Supabase CLI:
--   supabase db push
--
-- Or paste into the SQL editor at https://app.supabase.com → SQL Editor.

-- ─── users ──────────────────────────────────────────────────────────────
create table if not exists public.users (
  clerk_id            text primary key,
  email               text unique,
  first_name          text,
  last_name           text,
  stripe_customer_id  text unique,
  created_at          timestamptz not null default now(),
  updated_at          timestamptz not null default now()
);

create index if not exists users_stripe_customer_id_idx
  on public.users (stripe_customer_id);

alter table public.users enable row level security;

-- Users can SELECT their own row. The auth.jwt() ->> 'sub' claim is the
-- Clerk user id when the JWT comes from a Clerk-issued token.
create policy "users self-select" on public.users
  for select using (clerk_id = auth.jwt() ->> 'sub');

-- Updates happen exclusively via service role (server actions / webhooks).
-- No public update/delete policy on purpose.

-- ─── subscriptions ──────────────────────────────────────────────────────
create table if not exists public.subscriptions (
  stripe_subscription_id  text primary key,
  stripe_customer_id      text not null references public.users(stripe_customer_id) on delete cascade,
  status                  text not null,
  price_id                text,
  current_period_end      timestamptz,
  canceled_at             timestamptz,
  created_at              timestamptz not null default now()
);

alter table public.subscriptions enable row level security;

-- Users can read their own subscriptions.
create policy "subscriptions self-select" on public.subscriptions
  for select using (
    stripe_customer_id in (
      select stripe_customer_id from public.users where clerk_id = auth.jwt() ->> 'sub'
    )
  );

-- Inserts/updates happen via the Stripe webhook handler using the service
-- role key — no public insert/update policy needed.
