-- =============================================================================
-- Migration: 20260419000004_consolidate_policies
-- V#35 — Consolida policies duplicadas em plans, features, plan_features e
-- subscriptions. Remove legado redundante e documenta as que ficam.
--
-- Análise (auditada via pg_policies):
--   • plans/features/plan_features: cada uma tem "read * (auth)" duplicado
--     com "*_read_authenticated" (mesmo USING true). Removidos os legados.
--   • subscriptions:
--      - "subscriptions read own" (USING user_id = auth.uid()) é SUBSET de
--        "subscriptions_read_own" (USING user_id = auth.uid() OR is_saas_admin())
--      - "subscriptions_select_own_personal" (user_id = auth.uid() AND tenant_id IS NULL)
--        é SUBSET de "subscriptions_read_own"
--      - "subscriptions_no_direct_update" (USING false) é no-op em OR com
--        "subscriptions_update_only_saas_admin"
--     Removidas as 3 redundâncias.
-- =============================================================================

-- ─────────────────────────────────────────────────────────────────────────
-- Drops dos legados redundantes
-- -----------------------------------------------------------------------------
DROP POLICY IF EXISTS "read plans (auth)"          ON public.plans;
DROP POLICY IF EXISTS "read features (auth)"       ON public.features;
DROP POLICY IF EXISTS "read plan_features (auth)"  ON public.plan_features;

DROP POLICY IF EXISTS "subscriptions read own"             ON public.subscriptions;
DROP POLICY IF EXISTS "subscriptions_select_own_personal"  ON public.subscriptions;
DROP POLICY IF EXISTS "subscriptions_no_direct_update"     ON public.subscriptions;

-- ─────────────────────────────────────────────────────────────────────────
-- COMMENT ON POLICY — documenta escopo das que ficaram
-- -----------------------------------------------------------------------------
COMMENT ON POLICY plans_read_authenticated         ON public.plans          IS 'Qualquer usuário autenticado lê o catálogo de planos (vitrine, upgrade UI).';
COMMENT ON POLICY plans_write_saas_admin           ON public.plans          IS 'Somente saas_admin escreve. DELETE deve ser via RPC delete_plan_safe (V#36).';

COMMENT ON POLICY features_read_authenticated      ON public.features       IS 'Qualquer logado lê o catálogo de features.';
COMMENT ON POLICY features_write_saas_admin        ON public.features       IS 'Somente saas_admin escreve. DELETE = soft delete via is_active=false (V#40).';

COMMENT ON POLICY plan_features_read_authenticated ON public.plan_features  IS 'Qualquer logado lê o vínculo plano↔feature (necessário para entitlements).';
COMMENT ON POLICY plan_features_write_saas_admin   ON public.plan_features  IS 'Somente saas_admin escreve.';

COMMENT ON POLICY subscriptions_read_own                    ON public.subscriptions IS 'Dono da assinatura (user_id) ou saas_admin. Cobre o caso pessoal.';
COMMENT ON POLICY subscriptions_select_for_tenant_members   ON public.subscriptions IS 'Membros ativos do tenant leem assinaturas do tenant.';
COMMENT ON POLICY "subscriptions: read if linked owner_users" ON public.subscriptions IS 'Caso especial: usuários ligados ao owner via owner_users (terapeutas de uma clínica que precisam ver a assinatura do owner).';
COMMENT ON POLICY subscriptions_insert_own_personal         ON public.subscriptions IS 'Usuário cria a própria assinatura pessoal (intent → conversion).';
COMMENT ON POLICY subscriptions_update_only_saas_admin      ON public.subscriptions IS 'UPDATE direto somente via saas_admin. Mudanças de tenant devem passar por RPC dedicada.';
