-- ASA Module: payments-basic (entitlement architecture)
-- Migration: 003_create_entitlements
-- Creates deterministic entitlement tables for feature/limit checks.
--
-- Usage:
-- 1. Apply this migration in Supabase SQL Editor
-- 2. Seed plan_features with your plan configuration
-- 3. Use requireEntitlement() and requireLimit() guards in route handlers

-- Plan → feature/limit mapping (seed data, admin-editable)
create table if not exists plan_features (
  id uuid primary key default gen_random_uuid(),
  plan_key text not null,
  feature_key text not null,
  feature_type text not null check (feature_type in ('boolean', 'number')),
  value text not null,
  unique(plan_key, feature_key)
);

-- Materialized entitlements per user (source of truth for app)
create table if not exists entitlements (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users(id) on delete cascade,
  feature_key text not null,
  feature_type text not null check (feature_type in ('boolean', 'number')),
  value text not null,
  source text not null default 'plan' check (source in ('plan', 'override')),
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now(),
  unique(user_id, feature_key)
);

-- RLS: users can only read their own entitlements
alter table entitlements enable row level security;

create policy "Users can read own entitlements"
  on entitlements for select
  using (auth.uid() = user_id);

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

-- RLS: plan_features readable by all authenticated users (public pricing info)
alter table plan_features enable row level security;

create policy "Anyone can read plan features"
  on plan_features for select
  using (true);

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

-- Indexes
create index if not exists idx_entitlements_user_id on entitlements(user_id);
create index if not exists idx_entitlements_feature on entitlements(user_id, feature_key);
create index if not exists idx_plan_features_plan on plan_features(plan_key);
