-- Migration: v75-payment-orders.sql
-- Description: Tracks completed payment orders and guarantees idempotency for automated checkout fulfillment

CREATE TABLE IF NOT EXISTS public.payment_orders (
  id TEXT PRIMARY KEY, -- Polar or payment processor Order ID
  processor TEXT NOT NULL DEFAULT 'polar',
  user_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
  username TEXT NOT NULL,
  item_id TEXT NOT NULL,
  amount_cents INTEGER NOT NULL DEFAULT 0,
  currency TEXT NOT NULL DEFAULT 'usd',
  customer_email TEXT,
  status TEXT NOT NULL DEFAULT 'fulfilled',
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  metadata JSONB DEFAULT '{}'::jsonb
);

CREATE INDEX IF NOT EXISTS idx_payment_orders_user_id ON public.payment_orders(user_id);
CREATE INDEX IF NOT EXISTS idx_payment_orders_username ON public.payment_orders(username);
CREATE INDEX IF NOT EXISTS idx_payment_orders_created_at ON public.payment_orders(created_at DESC);

-- Enable RLS and restrict direct client access
ALTER TABLE public.payment_orders ENABLE ROW LEVEL SECURITY;

-- Allow users to read only their own orders
CREATE POLICY "Users can read own payment orders"
  ON public.payment_orders
  FOR SELECT
  TO authenticated
  USING (auth.uid() = user_id);

-- Revoke all modifications from public/anon/authenticated (fulfillment via service_role only)
REVOKE INSERT, UPDATE, DELETE ON public.payment_orders FROM anon, authenticated;
GRANT ALL ON public.payment_orders TO service_role;
