/**
 * Tenant license fetch from Supabase — RLS read policy.
 *
 * Arch change: each tenant's server now reads its signed term license
 * directly from Supabase cloud `tenant_licenses` (the SuperAdmin writes
 * there when it issues a license). The tenant server uses the anon key
 * already in `SUPABASE_KEY` / `VITE_SUPABASE_ANON_KEY` and the API layer
 * scopes by `tenant_id` on the request. The RLS policy below is the
 * defense-in-depth layer: it allows the `anon` role to SELECT from the
 * table, and the application-layer `.eq('tenant_id', ...)` filter ensures
 * each tenant only sees its own row. (A stronger per-tenant JWT-claim
 * scoping would require minting a tenant-specific JWT — out of scope.
 * This is the trade-off the user signed off on: couples licensing to
 * Supabase RLS design, no new secret to manage.)
 *
 * Pure-SQL migration: runs against the Supabase Postgres when
 * `DB_CLIENT=pg`. Safe no-op on SQLite (`isPg` guard), so the same
 * migration runs in dev/local without raising.
 */

exports.up = async function (knex) {
  const isPg = knex.client.config.client === 'pg';
  if (!isPg) {
    // SQLite: this migration is only meaningful against the Supabase
    // Postgres backend. Local SQLite has no RLS — the application
    // layer (`SupabaseLicenseService.fetchActiveLicense`) filters every
    // fetch by `tenant_id`. Nothing to apply.
    return;
  }

  // Enable RLS. Idempotent (Postgres returns success if already enabled,
  // we wrap in IF EXISTS-style guard to be safe).
  await knex.schema.raw(`ALTER TABLE public.tenant_licenses ENABLE ROW LEVEL SECURITY;`);

  // Read policy for the anon role. Defence-in-depth: the application
  // layer scopes every read by `tenant_id`, so even if the policy is
  // permissive we only ever return the row that matches the requested
  // tenant. A stricter policy would require a custom JWT claim per
  // tenant, which is intentionally deferred.
  await knex.schema.raw(`
    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 $$;
  `);

  // Belt-and-braces: only the SuperAdmin should mutate licenses, and it
  // does so via the SECURITY DEFINER RPC functions installed by migration
  // 2026072900000100_superadmin_rpc_functions.js — never directly via
  // the anon key. Mutations from anon are blocked by the absence of a
  // WRITE policy under RLS. Reads from the anon key are allowed by the
  // policy above; the application layer scopes every read by
  // `tenant_id`.
};

exports.down = async function (knex) {
  const isPg = knex.client.config.client === 'pg';
  if (!isPg) return;

  await knex.schema.raw(`
    DO $$
    BEGIN
      IF EXISTS (
        SELECT 1 FROM pg_policies
        WHERE schemaname = 'public'
          AND tablename  = 'tenant_licenses'
          AND policyname = 'tenant_license_anon_read'
      ) THEN
        DROP POLICY tenant_license_anon_read ON public.tenant_licenses;
      END IF;
    END $$;
  `);

  await knex.schema.raw(`ALTER TABLE public.tenant_licenses DISABLE ROW LEVEL SECURITY;`);
};
