-- ASA Module: payments-basic
-- Migration: 002_create_subscriptions
-- Creates subscriptions table for Stripe billing

-- Subscription state machine: active, past_due, trialing, incomplete, canceled, unpaid
-- IMPORTANT: past_due = "still has access" (Stripe retrying payment)
create table if not exists subscriptions (
  id uuid primary key default gen_random_uuid(),
  user_id uuid references profiles(id) on delete cascade not null,
  stripe_customer_id text,
  stripe_subscription_id text,
  plan text not null default 'free',
  status text not null default 'active'
    check (status in ('active', 'past_due', 'trialing', 'incomplete', 'canceled', 'unpaid')),
  current_period_end timestamptz,
  cancel_at_period_end boolean not null default false,
  created_at timestamptz default now(),
  updated_at timestamptz default now()
);

-- RLS policies (correct WITH CHECK for all operations)
alter table subscriptions enable row level security;

create policy "Users can view own subscription"
  on subscriptions for select
  using (auth.uid() = user_id);

-- No direct insert/update from client — managed by webhook handler via admin client

-- Webhook event idempotency table
create table if not exists webhook_events (
  event_id text primary key,
  event_type text not null,
  processed_at timestamptz default now()
);

-- No RLS on webhook_events — accessed only via admin client (server-side)
alter table webhook_events enable row level security;
-- No policies = deny all client access (correct — admin client bypasses RLS)

-- Indexes
create index if not exists idx_subscriptions_user_id on subscriptions(user_id);
create index if not exists idx_subscriptions_stripe_customer on subscriptions(stripe_customer_id);
create index if not exists idx_webhook_events_type on webhook_events(event_type);
