-- ============================================================================
-- Tenant license fetch from Supabase — direct `psql` apply.
--
-- Use this when you need to apply the RLS policy to the Supabase project
-- directly (e.g. via the Supabase SQL editor or `psql -f`). The Knex
-- migration 2026072900000000_tenant_licenses_rls_read_policy.js does the
-- same thing via the project's migration runner.
--
-- Apply:
--   psql "postgresql://postgres:<password>@<host>:5432/postgres" -f \
--     sql/20260729_tenant_licenses_rls_read_policy.sql
--
-- Or paste into the Supabase SQL editor and run.
-- ============================================================================

ALTER TABLE public.tenant_licenses ENABLE ROW LEVEL SECURITY;

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_policies
    WHERE schemaname = 'public'
      AND tablename  = 'tenant_licenses'
      AND policyname = 'tenant_license_anon_read'
  ) THEN
    CREATE POLICY tenant_license_anon_read
      ON public.tenant_licenses
      FOR SELECT
      TO anon, authenticated
      USING (true);
  END IF;
END $$;

-- Notes for the operator:
-- • The SuperAdmin writes to this table via the anon key + the
--   SECURITY DEFINER RPC function `upsert_license_cloud` installed by
--   `sql/20260729_superadmin_rpc_functions.sql`. The service-role key
--   is not used anywhere in this stack.
-- • The tenant server reads via the anon key + an application-layer
--   `.eq('tenant_id', <uuid>)` filter. Even though RLS is permissive for
--   the anon role, the API filter ensures each tenant only sees its own
--   row. This is the documented trade-off — see
--   SUPERADMIN_MULTITENANT_DOCUMENTATION.md §2.
-- • No INSERT/UPDATE/DELETE policies are created for the anon role, so
--   a tenant server cannot accidentally write to tenant_licenses even
--   if a bug attempts to.
