-- RLS Policies
-- Gerado automaticamente em 2026-05-11T16:53:50.939Z
-- Enable RLS: 137 tabelas
-- Policies: 357

-- Enable RLS
ALTER TABLE public.addon_credits ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.addon_products ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.addon_transactions ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.agenda_bloqueios ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.agenda_configuracoes ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.agenda_eventos ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.agenda_excecoes ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.agenda_online_slots ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.agenda_regras_semanais ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.agenda_slots_bloqueados_semanais ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.agenda_slots_regras ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.agendador_configuracoes ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.agendador_solicitacoes ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.audit_logs ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.billing_contracts ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.commitment_services ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.commitment_time_logs ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.company_profiles ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.contact_email_types ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.contact_emails ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.contact_phones ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.contact_types ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.conversation_assignments ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.conversation_autoreply_log ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.conversation_autoreply_settings ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.conversation_bot_sessions ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.conversation_bots ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.conversation_messages ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.conversation_notes ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.conversation_optout_keywords ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.conversation_optouts ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.conversation_sla_breaches ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.conversation_sla_rules ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.conversation_tags ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.conversation_thread_tags ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.determined_commitment_fields ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.determined_commitments ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.dev_auditoria_items ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.dev_comparison_competitor_status ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.dev_comparison_matrix ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.dev_competitor_features ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.dev_competitors ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.dev_generation_log ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.dev_roadmap_items ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.dev_roadmap_phases ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.dev_test_items ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.dev_user_credentials ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.dev_verificacoes_items ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.document_access_logs ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.document_generated ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.document_share_links ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.document_signatures ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.document_templates ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.documents ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.email_layout_config ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.email_templates_global ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.email_templates_tenant ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.entitlements_invalidation ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.features ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.feriados ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.financial_categories ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.financial_exceptions ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.financial_records ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.global_notices ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.insurance_plan_services ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.insurance_plans ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.login_carousel_slides ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.math_challenges ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.medicos ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.module_features ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.modules ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.notice_dismissals ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.notification_channels ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.notification_logs ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.notification_preferences ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.notification_queue ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.notification_schedules ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.notification_templates ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.notifications ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.owner_users ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.patient_contacts ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.patient_discounts ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.patient_group_patient ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.patient_groups ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.patient_intake_requests ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.patient_invite_attempts ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.patient_invites ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.patient_patient_tag ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.patient_status_history ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.patient_support_contacts ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.patient_tags ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.patient_timeline ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.patients ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.payment_settings ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.plan_features ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.plan_prices ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.plan_public ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.plan_public_bullets ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.plans ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.professional_pricing ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.public_submission_attempts ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.recurrence_exceptions ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.recurrence_rule_services ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.recurrence_rules ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.saas_admins ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.saas_doc_votos ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.saas_docs ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.saas_faq ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.saas_faq_itens ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.saas_security_config ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.saas_twilio_config ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.services ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.session_reminder_logs ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.session_reminder_settings ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.submission_rate_limits ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.subscription_events ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.subscription_intents_legacy ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.subscription_intents_personal ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.subscription_intents_tenant ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.subscriptions ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.support_sessions ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.tenant_feature_exceptions_log ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.tenant_features ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.tenant_invites ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.tenant_members ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.tenant_modules ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.tenants ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.therapist_payout_records ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.therapist_payouts ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.twilio_subaccount_usage ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.user_settings ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.whatsapp_connection_incidents ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.whatsapp_credit_packages ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.whatsapp_credit_purchases ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.whatsapp_credits_balance ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.whatsapp_credits_transactions ENABLE ROW LEVEL SECURITY;

-- Policies
CREATE POLICY addon_credits_admin_select ON public.addon_credits FOR SELECT TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.saas_admins
  WHERE (saas_admins.user_id = auth.uid()))));

CREATE POLICY addon_credits_admin_write ON public.addon_credits TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.saas_admins
  WHERE (saas_admins.user_id = auth.uid())))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.saas_admins
  WHERE (saas_admins.user_id = auth.uid()))));

CREATE POLICY addon_credits_select_own ON public.addon_credits FOR SELECT TO authenticated USING ((public.is_tenant_member(tenant_id) OR (owner_id = auth.uid())));

CREATE POLICY addon_products_admin_all ON public.addon_products TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.saas_admins
  WHERE (saas_admins.user_id = auth.uid())))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.saas_admins
  WHERE (saas_admins.user_id = auth.uid()))));

CREATE POLICY addon_products_select_authenticated ON public.addon_products FOR SELECT TO authenticated USING (((deleted_at IS NULL) AND (is_active = true) AND (is_visible = true)));

CREATE POLICY addon_transactions_admin_insert ON public.addon_transactions FOR INSERT TO authenticated WITH CHECK ((EXISTS ( SELECT 1
   FROM public.saas_admins sa
  WHERE (sa.user_id = auth.uid()))));

CREATE POLICY addon_transactions_admin_select ON public.addon_transactions FOR SELECT TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.saas_admins
  WHERE (saas_admins.user_id = auth.uid()))));

CREATE POLICY addon_transactions_select_own ON public.addon_transactions FOR SELECT TO authenticated USING ((public.is_tenant_member(tenant_id) OR (owner_id = auth.uid())));

CREATE POLICY agenda_configuracoes_clinic_read ON public.agenda_configuracoes FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.view'::text)));

CREATE POLICY agenda_configuracoes_clinic_write ON public.agenda_configuracoes USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text)));

CREATE POLICY agenda_configuracoes_owner ON public.agenda_configuracoes USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY agenda_eventos_delete ON public.agenda_eventos FOR DELETE USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.delete'::text)));

CREATE POLICY agenda_eventos_insert ON public.agenda_eventos FOR INSERT WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.create'::text)));

CREATE POLICY agenda_eventos_owner_all ON public.agenda_eventos TO authenticated USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY agenda_eventos_select ON public.agenda_eventos FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.view'::text)));

CREATE POLICY agenda_eventos_update ON public.agenda_eventos FOR UPDATE USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text)));

CREATE POLICY agenda_excecoes_owner ON public.agenda_excecoes USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY agenda_excecoes_select ON public.agenda_excecoes FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.view'::text)));

CREATE POLICY agenda_excecoes_write ON public.agenda_excecoes USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text)));

CREATE POLICY agenda_online_slots_owner ON public.agenda_online_slots USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY agenda_online_slots_select ON public.agenda_online_slots FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.view'::text)));

CREATE POLICY agenda_online_slots_write ON public.agenda_online_slots USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text)));

CREATE POLICY agenda_regras_semanais_owner ON public.agenda_regras_semanais USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY agenda_regras_semanais_select ON public.agenda_regras_semanais FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.view'::text)));

CREATE POLICY agenda_regras_semanais_write ON public.agenda_regras_semanais USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text)));

CREATE POLICY agenda_slots_bloqueados_semanais_select ON public.agenda_slots_bloqueados_semanais FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.view'::text)));

CREATE POLICY agenda_slots_bloqueados_semanais_write ON public.agenda_slots_bloqueados_semanais USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text)));

CREATE POLICY agenda_slots_regras_select ON public.agenda_slots_regras FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.view'::text)));

CREATE POLICY agenda_slots_regras_write ON public.agenda_slots_regras USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text)));

CREATE POLICY agendador_cfg_public_read ON public.agendador_configuracoes FOR SELECT TO anon USING (((ativo = true) AND (link_slug IS NOT NULL)));

CREATE POLICY agendador_cfg_select ON public.agendador_configuracoes FOR SELECT USING ((auth.uid() = owner_id));

CREATE POLICY agendador_cfg_write ON public.agendador_configuracoes USING ((auth.uid() = owner_id)) WITH CHECK ((auth.uid() = owner_id));

CREATE POLICY agendador_sol_owner_select ON public.agendador_solicitacoes FOR SELECT USING ((auth.uid() = owner_id));

CREATE POLICY agendador_sol_owner_write ON public.agendador_solicitacoes USING ((auth.uid() = owner_id)) WITH CHECK ((auth.uid() = owner_id));

CREATE POLICY agendador_sol_patient_read ON public.agendador_solicitacoes FOR SELECT TO authenticated USING (((auth.uid() = user_id) OR (auth.uid() = owner_id)));

CREATE POLICY agendador_sol_public_insert ON public.agendador_solicitacoes FOR INSERT TO anon WITH CHECK (true);

CREATE POLICY "audit_logs: no direct delete" ON public.audit_logs FOR DELETE TO authenticated USING (false);

CREATE POLICY "audit_logs: no direct insert" ON public.audit_logs FOR INSERT TO authenticated WITH CHECK (false);

CREATE POLICY "audit_logs: no direct update" ON public.audit_logs FOR UPDATE TO authenticated USING (false) WITH CHECK (false);

CREATE POLICY "audit_logs: select tenant" ON public.audit_logs FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "autoreply_log: select" ON public.conversation_autoreply_log FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_autoreply_log.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "autoreply_settings: insert" ON public.conversation_autoreply_settings FOR INSERT TO authenticated WITH CHECK ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_autoreply_settings.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "autoreply_settings: select" ON public.conversation_autoreply_settings FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_autoreply_settings.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "autoreply_settings: update" ON public.conversation_autoreply_settings FOR UPDATE TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_autoreply_settings.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "billing_contracts: delete" ON public.billing_contracts FOR DELETE TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY "billing_contracts: insert" ON public.billing_contracts FOR INSERT TO authenticated WITH CHECK (((owner_id = auth.uid()) AND (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "billing_contracts: select" ON public.billing_contracts FOR SELECT TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "billing_contracts: update" ON public.billing_contracts FOR UPDATE TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin())) WITH CHECK (((owner_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY bloqueios_delete ON public.agenda_bloqueios FOR DELETE TO authenticated USING ((owner_id = auth.uid()));

CREATE POLICY bloqueios_insert ON public.agenda_bloqueios FOR INSERT TO authenticated WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY bloqueios_select_clinic ON public.agenda_bloqueios FOR SELECT TO authenticated USING ((tenant_id IN ( SELECT tenant_members.tenant_id
   FROM public.tenant_members
  WHERE ((tenant_members.user_id = auth.uid()) AND (tenant_members.role = ANY (ARRAY['admin'::text, 'clinic_admin'::text, 'tenant_admin'::text, 'secretary'::text]))))));

CREATE POLICY bloqueios_select_own ON public.agenda_bloqueios FOR SELECT TO authenticated USING ((owner_id = auth.uid()));

CREATE POLICY bloqueios_update ON public.agenda_bloqueios FOR UPDATE TO authenticated USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY "bot_sessions: select membros" ON public.conversation_bot_sessions FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = conversation_bot_sessions.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "bot_sessions: write service_role" ON public.conversation_bot_sessions TO service_role USING (true) WITH CHECK (true);

CREATE POLICY clinic_admin_read_all_docs ON public.saas_docs FOR SELECT TO authenticated USING (((ativo = true) AND (EXISTS ( SELECT 1
   FROM public.profiles
  WHERE ((profiles.id = auth.uid()) AND (profiles.role = ANY (ARRAY['clinic_admin'::text, 'tenant_admin'::text])))))));

CREATE POLICY "commitment_services: tenant_member" ON public.commitment_services TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.services s
  WHERE ((s.id = commitment_services.service_id) AND ((s.owner_id = auth.uid()) OR public.is_saas_admin() OR (s.tenant_id IN ( SELECT tm.tenant_id
           FROM public.tenant_members tm
          WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))))))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.services s
  WHERE ((s.id = commitment_services.service_id) AND ((s.owner_id = auth.uid()) OR public.is_saas_admin())))));

CREATE POLICY company_profiles_delete ON public.company_profiles FOR DELETE USING ((EXISTS ( SELECT 1
   FROM public.tenant_members
  WHERE ((tenant_members.tenant_id = company_profiles.tenant_id) AND (tenant_members.user_id = auth.uid())))));

CREATE POLICY company_profiles_insert ON public.company_profiles FOR INSERT WITH CHECK ((EXISTS ( SELECT 1
   FROM public.tenant_members
  WHERE ((tenant_members.tenant_id = company_profiles.tenant_id) AND (tenant_members.user_id = auth.uid())))));

CREATE POLICY company_profiles_select ON public.company_profiles FOR SELECT USING ((EXISTS ( SELECT 1
   FROM public.tenant_members
  WHERE ((tenant_members.tenant_id = company_profiles.tenant_id) AND (tenant_members.user_id = auth.uid())))));

CREATE POLICY company_profiles_update ON public.company_profiles FOR UPDATE USING ((EXISTS ( SELECT 1
   FROM public.tenant_members
  WHERE ((tenant_members.tenant_id = company_profiles.tenant_id) AND (tenant_members.user_id = auth.uid()))))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.tenant_members
  WHERE ((tenant_members.tenant_id = company_profiles.tenant_id) AND (tenant_members.user_id = auth.uid())))));

CREATE POLICY "contact_email_types: manage custom" ON public.contact_email_types TO authenticated USING (((is_system = false) AND (tenant_id IS NOT NULL) AND (public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = contact_email_types.tenant_id) AND (tm.status = 'active'::text))))))) WITH CHECK (((is_system = false) AND (tenant_id IS NOT NULL) AND (public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = contact_email_types.tenant_id) AND (tm.status = 'active'::text)))))));

CREATE POLICY "contact_email_types: select" ON public.contact_email_types FOR SELECT TO authenticated USING (((tenant_id IS NULL) OR public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = contact_email_types.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "contact_emails: all tenant" ON public.contact_emails TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = contact_emails.tenant_id) AND (tm.status = 'active'::text)))))) WITH CHECK ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = contact_emails.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "contact_phones: all tenant" ON public.contact_phones TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = contact_phones.tenant_id) AND (tm.status = 'active'::text)))))) WITH CHECK ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = contact_phones.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "contact_types: manage custom" ON public.contact_types TO authenticated USING (((is_system = false) AND (tenant_id IS NOT NULL) AND (public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = contact_types.tenant_id) AND (tm.status = 'active'::text))))))) WITH CHECK (((is_system = false) AND (tenant_id IS NOT NULL) AND (public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = contact_types.tenant_id) AND (tm.status = 'active'::text)))))));

CREATE POLICY "contact_types: select" ON public.contact_types FOR SELECT TO authenticated USING (((tenant_id IS NULL) OR public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = contact_types.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "conv_assign: insert tenant" ON public.conversation_assignments FOR INSERT TO authenticated WITH CHECK (((assigned_by = auth.uid()) AND (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_assignments.tenant_id) AND (tm.status = 'active'::text)))) AND ((assigned_to IS NULL) OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm2
  WHERE ((tm2.user_id = conversation_assignments.assigned_to) AND (tm2.tenant_id = conversation_assignments.tenant_id) AND (tm2.status = 'active'::text)))))));

CREATE POLICY "conv_assign: select tenant" ON public.conversation_assignments FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_assignments.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "conv_assign: update tenant" ON public.conversation_assignments FOR UPDATE TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_assignments.tenant_id) AND (tm.status = 'active'::text))))) WITH CHECK (((assigned_by = auth.uid()) AND ((assigned_to IS NULL) OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm2
  WHERE ((tm2.user_id = conversation_assignments.assigned_to) AND (tm2.tenant_id = conversation_assignments.tenant_id) AND (tm2.status = 'active'::text)))))));

CREATE POLICY "conv_bots: select membros" ON public.conversation_bots FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = conversation_bots.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "conv_bots: write admins" ON public.conversation_bots TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = conversation_bots.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.role = ANY (ARRAY['clinic_admin'::text, 'tenant_admin'::text])) AND (tm.status = 'active'::text)))))) WITH CHECK ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = conversation_bots.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.role = ANY (ARRAY['clinic_admin'::text, 'tenant_admin'::text])) AND (tm.status = 'active'::text))))));

CREATE POLICY "conv_msg: no direct delete" ON public.conversation_messages FOR DELETE TO authenticated USING (false);

CREATE POLICY "conv_msg: no direct insert" ON public.conversation_messages FOR INSERT TO authenticated WITH CHECK (false);

CREATE POLICY "conv_msg: select tenant" ON public.conversation_messages FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "conv_msg: update kanban" ON public.conversation_messages FOR UPDATE TO authenticated USING ((tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))) WITH CHECK ((tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))));

CREATE POLICY "conv_notes: insert tenant members" ON public.conversation_notes FOR INSERT TO authenticated WITH CHECK (((created_by = auth.uid()) AND (public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_notes.tenant_id) AND (tm.status = 'active'::text)))))));

CREATE POLICY "conv_notes: select tenant members" ON public.conversation_notes FOR SELECT TO authenticated USING (((deleted_at IS NULL) AND (public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_notes.tenant_id) AND (tm.status = 'active'::text)))))));

CREATE POLICY "conv_notes: update creator or saas" ON public.conversation_notes FOR UPDATE TO authenticated USING (((deleted_at IS NULL) AND ((created_by = auth.uid()) OR public.is_saas_admin()))) WITH CHECK ((created_by = ( SELECT conversation_notes_1.created_by
   FROM public.conversation_notes conversation_notes_1
  WHERE (conversation_notes_1.id = conversation_notes_1.id))));

CREATE POLICY "conv_tags: delete custom" ON public.conversation_tags FOR DELETE TO authenticated USING (((is_system = false) AND (tenant_id IS NOT NULL) AND (public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_tags.tenant_id) AND (tm.status = 'active'::text)))))));

CREATE POLICY "conv_tags: insert custom" ON public.conversation_tags FOR INSERT TO authenticated WITH CHECK (((tenant_id IS NOT NULL) AND (is_system = false) AND (public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_tags.tenant_id) AND (tm.status = 'active'::text)))))));

CREATE POLICY "conv_tags: select" ON public.conversation_tags FOR SELECT TO authenticated USING (((tenant_id IS NULL) OR public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_tags.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "conv_tags: update custom" ON public.conversation_tags FOR UPDATE TO authenticated USING (((is_system = false) AND (tenant_id IS NOT NULL) AND (public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_tags.tenant_id) AND (tm.status = 'active'::text))))))) WITH CHECK ((is_system = false));

CREATE POLICY "conv_thread_tags: delete" ON public.conversation_thread_tags FOR DELETE TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_thread_tags.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "conv_thread_tags: insert" ON public.conversation_thread_tags FOR INSERT TO authenticated WITH CHECK (((tagged_by = auth.uid()) AND (public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_thread_tags.tenant_id) AND (tm.status = 'active'::text)))))));

CREATE POLICY "conv_thread_tags: select" ON public.conversation_thread_tags FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_thread_tags.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY ctl_delete_for_active_member ON public.commitment_time_logs FOR DELETE TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = commitment_time_logs.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))));

CREATE POLICY ctl_insert_for_active_member ON public.commitment_time_logs FOR INSERT TO authenticated WITH CHECK ((tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))));

CREATE POLICY ctl_select_for_active_member ON public.commitment_time_logs FOR SELECT TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = commitment_time_logs.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))));

CREATE POLICY ctl_update_for_active_member ON public.commitment_time_logs FOR UPDATE TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = commitment_time_logs.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = commitment_time_logs.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))));

CREATE POLICY "dal: tenant members can insert" ON public.document_access_logs FOR INSERT TO authenticated WITH CHECK ((tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))));

CREATE POLICY "dal: tenant members can select" ON public.document_access_logs FOR SELECT USING ((tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))));

CREATE POLICY dc_delete_custom_for_active_member ON public.determined_commitments FOR DELETE TO authenticated USING (((is_native = false) AND (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = determined_commitments.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY dc_insert_for_active_member ON public.determined_commitments FOR INSERT TO authenticated WITH CHECK ((tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))));

CREATE POLICY dc_select_for_active_member ON public.determined_commitments FOR SELECT TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = determined_commitments.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))));

CREATE POLICY dc_update_for_active_member ON public.determined_commitments FOR UPDATE TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = determined_commitments.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = determined_commitments.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))));

CREATE POLICY dcf_delete_for_active_member ON public.determined_commitment_fields FOR DELETE TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = determined_commitment_fields.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))));

CREATE POLICY dcf_insert_for_active_member ON public.determined_commitment_fields FOR INSERT TO authenticated WITH CHECK ((tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))));

CREATE POLICY dcf_select_for_active_member ON public.determined_commitment_fields FOR SELECT TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = determined_commitment_fields.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))));

CREATE POLICY dcf_update_for_active_member ON public.determined_commitment_fields FOR UPDATE TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = determined_commitment_fields.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = determined_commitment_fields.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))));

CREATE POLICY "delete own" ON public.agenda_bloqueios FOR DELETE USING ((owner_id = auth.uid()));

CREATE POLICY dev_auditoria_items_saas_admin_all ON public.dev_auditoria_items TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY dev_comparison_competitor_status_saas_admin_all ON public.dev_comparison_competitor_status TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY dev_comparison_matrix_saas_admin_all ON public.dev_comparison_matrix TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY dev_competitor_features_saas_admin_all ON public.dev_competitor_features TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY dev_competitors_saas_admin_all ON public.dev_competitors TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY dev_creds_select_saas_admin ON public.dev_user_credentials FOR SELECT TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.profiles p
  WHERE ((p.id = auth.uid()) AND (p.role = 'saas_admin'::text)))));

CREATE POLICY dev_creds_write_saas_admin ON public.dev_user_credentials TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.profiles p
  WHERE ((p.id = auth.uid()) AND (p.role = 'saas_admin'::text))))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.profiles p
  WHERE ((p.id = auth.uid()) AND (p.role = 'saas_admin'::text)))));

CREATE POLICY dev_generation_log_saas_admin_all ON public.dev_generation_log TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY dev_roadmap_items_saas_admin_all ON public.dev_roadmap_items TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY dev_roadmap_phases_saas_admin_all ON public.dev_roadmap_phases TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY dev_test_items_saas_admin_all ON public.dev_test_items TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY dev_verificacoes_items_saas_admin_all ON public.dev_verificacoes_items TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY "dg: generator full access" ON public.document_generated USING ((gerado_por = auth.uid())) WITH CHECK ((gerado_por = auth.uid()));

CREATE POLICY "dg: tenant members can select" ON public.document_generated FOR SELECT USING ((tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))));

CREATE POLICY "documents: delete" ON public.documents FOR DELETE TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY "documents: insert" ON public.documents FOR INSERT TO authenticated WITH CHECK (((owner_id = auth.uid()) AND (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "documents: portal patient read" ON public.documents FOR SELECT TO authenticated USING (((compartilhado_portal = true) AND (patient_id IN ( SELECT p.id
   FROM public.patients p
  WHERE (p.user_id = auth.uid()))) AND ((expira_compartilhamento IS NULL) OR (expira_compartilhamento > now()))));

CREATE POLICY "documents: select" ON public.documents FOR SELECT TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "documents: update" ON public.documents FOR UPDATE TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin())) WITH CHECK (((owner_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY "ds: delete" ON public.document_signatures FOR DELETE TO authenticated USING (((signatario_id = auth.uid()) OR public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND (tm.role = ANY (ARRAY['tenant_admin'::text, 'admin'::text, 'owner'::text])))))));

CREATE POLICY "ds: insert" ON public.document_signatures FOR INSERT TO authenticated WITH CHECK (((tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))) AND ((signatario_id IS NULL) OR (signatario_id = auth.uid()))));

CREATE POLICY "ds: select" ON public.document_signatures FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "ds: update" ON public.document_signatures FOR UPDATE TO authenticated USING (((signatario_id = auth.uid()) OR public.is_saas_admin())) WITH CHECK (((signatario_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY "dsl: creator full access" ON public.document_share_links TO authenticated USING (((criado_por = auth.uid()) OR public.is_saas_admin())) WITH CHECK ((criado_por = auth.uid()));

CREATE POLICY "dt: global templates readable by all" ON public.document_templates FOR SELECT USING ((is_global = true));

CREATE POLICY "dt: owner can delete" ON public.document_templates FOR DELETE USING (((owner_id = auth.uid()) AND (is_global = false)));

CREATE POLICY "dt: owner can insert" ON public.document_templates FOR INSERT TO authenticated WITH CHECK (((is_global = false) AND (owner_id = auth.uid()) AND (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "dt: owner can update" ON public.document_templates FOR UPDATE USING (((owner_id = auth.uid()) AND (is_global = false))) WITH CHECK (((owner_id = auth.uid()) AND (is_global = false)));

CREATE POLICY "dt: saas admin can delete global" ON public.document_templates FOR DELETE USING (((is_global = true) AND public.is_saas_admin()));

CREATE POLICY "dt: saas admin can insert global" ON public.document_templates FOR INSERT TO authenticated WITH CHECK (((is_global = true) AND public.is_saas_admin()));

CREATE POLICY "dt: saas admin can update global" ON public.document_templates FOR UPDATE USING (((is_global = true) AND public.is_saas_admin())) WITH CHECK (((is_global = true) AND public.is_saas_admin()));

CREATE POLICY "dt: tenant members can select" ON public.document_templates FOR SELECT USING (((is_global = false) AND (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "email_layout_config: tenant_admin all" ON public.email_layout_config TO authenticated USING ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND (tm.role = ANY (ARRAY['tenant_admin'::text, 'admin'::text, 'owner'::text]))))))) WITH CHECK ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND (tm.role = ANY (ARRAY['tenant_admin'::text, 'admin'::text, 'owner'::text])))))));

CREATE POLICY "email_templates_tenant: tenant_admin all" ON public.email_templates_tenant TO authenticated USING ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND (tm.role = ANY (ARRAY['tenant_admin'::text, 'admin'::text, 'owner'::text]))))))) WITH CHECK ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND (tm.role = ANY (ARRAY['tenant_admin'::text, 'admin'::text, 'owner'::text])))))));

CREATE POLICY ent_inv_select_own ON public.entitlements_invalidation FOR SELECT USING (((owner_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY ent_inv_update_saas ON public.entitlements_invalidation FOR UPDATE USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY ent_inv_write_saas ON public.entitlements_invalidation FOR INSERT WITH CHECK (public.is_saas_admin());

CREATE POLICY faq_auth_read ON public.saas_faq FOR SELECT TO authenticated USING ((ativo = true));

CREATE POLICY faq_itens_auth_read ON public.saas_faq_itens FOR SELECT TO authenticated USING (((ativo = true) AND (EXISTS ( SELECT 1
   FROM public.saas_docs d
  WHERE ((d.id = saas_faq_itens.doc_id) AND (d.ativo = true))))));

CREATE POLICY faq_itens_saas_admin_write ON public.saas_faq_itens TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY faq_public_read ON public.saas_faq FOR SELECT USING (((publico = true) AND (ativo = true)));

CREATE POLICY faq_saas_admin_write ON public.saas_faq TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY features_read_authenticated ON public.features FOR SELECT TO authenticated USING (true);

CREATE POLICY features_write_saas_admin ON public.features TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY feriados_delete ON public.feriados FOR DELETE TO authenticated USING (((owner_id = auth.uid()) OR ((tenant_id IS NOT NULL) AND (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND (tm.role = ANY (ARRAY['tenant_admin'::text, 'admin'::text, 'owner'::text]))))))));

CREATE POLICY feriados_global_select ON public.feriados FOR SELECT USING ((tenant_id IS NULL));

CREATE POLICY feriados_insert ON public.feriados FOR INSERT TO authenticated WITH CHECK (((tenant_id IS NOT NULL) AND (owner_id = auth.uid()) AND (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY feriados_saas_delete ON public.feriados FOR DELETE USING ((EXISTS ( SELECT 1
   FROM public.saas_admins
  WHERE (saas_admins.user_id = auth.uid()))));

CREATE POLICY feriados_saas_insert ON public.feriados FOR INSERT TO authenticated WITH CHECK (((tenant_id IS NULL) AND (EXISTS ( SELECT 1
   FROM public.saas_admins sa
  WHERE (sa.user_id = auth.uid())))));

CREATE POLICY feriados_saas_select ON public.feriados FOR SELECT USING ((EXISTS ( SELECT 1
   FROM public.saas_admins
  WHERE (saas_admins.user_id = auth.uid()))));

CREATE POLICY feriados_select ON public.feriados FOR SELECT USING ((tenant_id IN ( SELECT tenant_members.tenant_id
   FROM public.tenant_members
  WHERE (tenant_members.user_id = auth.uid()))));

CREATE POLICY financial_categories_self ON public.financial_categories USING ((auth.uid() = user_id)) WITH CHECK ((auth.uid() = user_id));

CREATE POLICY "financial_exceptions: owner full access" ON public.financial_exceptions USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY "financial_exceptions: tenant members read clinic rules" ON public.financial_exceptions FOR SELECT USING (((owner_id IS NULL) AND (EXISTS ( SELECT 1
   FROM public.owner_users ou
  WHERE ((ou.owner_id = financial_exceptions.tenant_id) AND (ou.user_id = auth.uid()))))));

CREATE POLICY financial_records_self ON public.financial_records USING ((auth.uid() = owner_id)) WITH CHECK ((auth.uid() = owner_id));

CREATE POLICY financial_records_tenant_admin ON public.financial_records FOR SELECT USING (((tenant_id IS NOT NULL) AND public.is_tenant_admin(tenant_id)));

CREATE POLICY financial_records_tenant_member_read ON public.financial_records FOR SELECT USING (((tenant_id IS NOT NULL) AND (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = financial_records.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "global templates readable by authenticated" ON public.email_templates_global FOR SELECT USING ((auth.role() = 'authenticated'::text));

CREATE POLICY global_notices_saas_all ON public.global_notices TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.saas_admins
  WHERE (saas_admins.user_id = auth.uid()))));

CREATE POLICY global_notices_select ON public.global_notices FOR SELECT TO authenticated USING ((is_active = true));

CREATE POLICY "insert own" ON public.agenda_bloqueios FOR INSERT WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY "insurance_plan_services: tenant_member" ON public.insurance_plan_services TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.insurance_plans ip
  WHERE ((ip.id = insurance_plan_services.insurance_plan_id) AND ((ip.owner_id = auth.uid()) OR public.is_saas_admin() OR (ip.tenant_id IN ( SELECT tm.tenant_id
           FROM public.tenant_members tm
          WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))))))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.insurance_plans ip
  WHERE ((ip.id = insurance_plan_services.insurance_plan_id) AND ((ip.owner_id = auth.uid()) OR public.is_saas_admin())))));

CREATE POLICY "insurance_plans: delete" ON public.insurance_plans FOR DELETE TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY "insurance_plans: insert" ON public.insurance_plans FOR INSERT TO authenticated WITH CHECK (((owner_id = auth.uid()) AND (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "insurance_plans: select" ON public.insurance_plans FOR SELECT TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "insurance_plans: update" ON public.insurance_plans FOR UPDATE TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin())) WITH CHECK (((owner_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY "medicos: delete" ON public.medicos FOR DELETE TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY "medicos: insert" ON public.medicos FOR INSERT TO authenticated WITH CHECK (((owner_id = auth.uid()) AND (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "medicos: select" ON public.medicos FOR SELECT TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "medicos: update" ON public.medicos FOR UPDATE TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin())) WITH CHECK (((owner_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY module_features_read_authenticated ON public.module_features FOR SELECT TO authenticated USING (true);

CREATE POLICY module_features_write_saas_admin ON public.module_features TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY modules_read_authenticated ON public.modules FOR SELECT TO authenticated USING (true);

CREATE POLICY modules_write_saas_admin ON public.modules TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY notice_dismissals_own ON public.notice_dismissals TO authenticated USING ((user_id = auth.uid())) WITH CHECK ((user_id = auth.uid()));

CREATE POLICY notif_channels_delete ON public.notification_channels FOR DELETE TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY notif_channels_insert ON public.notification_channels FOR INSERT TO authenticated WITH CHECK ((public.is_saas_admin() OR ((owner_id = auth.uid()) AND (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))))));

CREATE POLICY notif_channels_modify ON public.notification_channels FOR UPDATE TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin())) WITH CHECK (((owner_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY notif_channels_select ON public.notification_channels FOR SELECT USING ((public.is_saas_admin() OR (owner_id = auth.uid()) OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY notif_logs_owner ON public.notification_logs FOR SELECT USING ((owner_id = auth.uid()));

CREATE POLICY notif_logs_tenant_member ON public.notification_logs FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY notif_prefs_owner ON public.notification_preferences USING (((owner_id = auth.uid()) AND (deleted_at IS NULL))) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY notif_queue_owner ON public.notification_queue FOR SELECT USING ((owner_id = auth.uid()));

CREATE POLICY notif_queue_tenant_member ON public.notification_queue FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY notif_schedules_owner ON public.notification_schedules USING (((owner_id = auth.uid()) AND (deleted_at IS NULL))) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY notif_templates_admin_all ON public.notification_templates TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.saas_admins
  WHERE (saas_admins.user_id = auth.uid())))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.saas_admins
  WHERE (saas_admins.user_id = auth.uid()))));

CREATE POLICY notif_templates_read_global ON public.notification_templates FOR SELECT TO authenticated USING (((deleted_at IS NULL) AND (((tenant_id IS NULL) AND (is_default = true)) OR (owner_id = auth.uid()) OR public.is_tenant_member(tenant_id))));

CREATE POLICY notif_templates_write_owner ON public.notification_templates TO authenticated USING (((owner_id = auth.uid()) OR public.is_tenant_member(tenant_id))) WITH CHECK (((owner_id = auth.uid()) OR public.is_tenant_member(tenant_id)));

CREATE POLICY "optout_kw: delete custom" ON public.conversation_optout_keywords FOR DELETE TO authenticated USING (((is_system = false) AND (tenant_id IS NOT NULL) AND (public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_optout_keywords.tenant_id) AND (tm.status = 'active'::text)))))));

CREATE POLICY "optout_kw: insert custom" ON public.conversation_optout_keywords FOR INSERT TO authenticated WITH CHECK (((tenant_id IS NOT NULL) AND (is_system = false) AND (public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_optout_keywords.tenant_id) AND (tm.status = 'active'::text)))))));

CREATE POLICY "optout_kw: select" ON public.conversation_optout_keywords FOR SELECT TO authenticated USING (((tenant_id IS NULL) OR public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_optout_keywords.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "optout_kw: update/delete custom" ON public.conversation_optout_keywords FOR UPDATE TO authenticated USING (((is_system = false) AND (tenant_id IS NOT NULL) AND (public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_optout_keywords.tenant_id) AND (tm.status = 'active'::text)))))));

CREATE POLICY "optouts: insert" ON public.conversation_optouts FOR INSERT TO authenticated WITH CHECK ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_optouts.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "optouts: select" ON public.conversation_optouts FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_optouts.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "optouts: update" ON public.conversation_optouts FOR UPDATE TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = conversation_optouts.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "owner only" ON public.notifications USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY "owner_users: user can read own links" ON public.owner_users FOR SELECT TO authenticated USING ((user_id = auth.uid()));

CREATE POLICY patient_contacts_select ON public.patient_contacts FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.view'::text)));

CREATE POLICY patient_contacts_write ON public.patient_contacts USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text)));

CREATE POLICY "patient_discounts: owner full access" ON public.patient_discounts USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY patient_group_patient_owner_all ON public.patient_group_patient TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.patients p
  WHERE ((p.id = patient_group_patient.patient_id) AND (p.owner_id = auth.uid()))))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.patients p
  WHERE ((p.id = patient_group_patient.patient_id) AND (p.owner_id = auth.uid())))));

CREATE POLICY patient_group_patient_select ON public.patient_group_patient FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.view'::text)));

CREATE POLICY patient_group_patient_write ON public.patient_group_patient USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text)));

CREATE POLICY patient_groups_owner_all ON public.patient_groups TO authenticated USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY patient_groups_select ON public.patient_groups FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.view'::text)));

CREATE POLICY patient_groups_write ON public.patient_groups USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text)));

CREATE POLICY patient_intake_requests_owner_all ON public.patient_intake_requests TO authenticated USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY patient_intake_requests_select ON public.patient_intake_requests FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.view'::text)));

CREATE POLICY patient_intake_requests_write ON public.patient_intake_requests USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text)));

CREATE POLICY patient_invite_attempts_owner_read ON public.patient_invite_attempts FOR SELECT TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY patient_invites_owner_all ON public.patient_invites TO authenticated USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY patient_invites_select ON public.patient_invites FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.view'::text)));

CREATE POLICY patient_invites_write ON public.patient_invites USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text)));

CREATE POLICY patient_patient_tag_owner_all ON public.patient_patient_tag TO authenticated USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY patient_patient_tag_select ON public.patient_patient_tag FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.view'::text)));

CREATE POLICY patient_patient_tag_write ON public.patient_patient_tag USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text)));

CREATE POLICY patient_tags_owner_all ON public.patient_tags TO authenticated USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY patient_tags_select ON public.patient_tags FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.view'::text)));

CREATE POLICY patient_tags_write ON public.patient_tags USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text)));

CREATE POLICY patients_delete ON public.patients FOR DELETE USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.delete'::text)));

CREATE POLICY patients_insert ON public.patients FOR INSERT WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.create'::text)));

CREATE POLICY patients_owner_all ON public.patients TO authenticated USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY patients_select ON public.patients FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.view'::text)));

CREATE POLICY patients_update ON public.patients FOR UPDATE USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text)));

CREATE POLICY "payment_settings: owner full access" ON public.payment_settings USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY "payment_settings: tenant_admin read" ON public.payment_settings FOR SELECT TO authenticated USING (((tenant_id IS NOT NULL) AND (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND (tm.role = ANY (ARRAY['tenant_admin'::text, 'admin'::text, 'owner'::text])))))));

CREATE POLICY plan_features_read_authenticated ON public.plan_features FOR SELECT TO authenticated USING (true);

CREATE POLICY plan_features_write_saas_admin ON public.plan_features TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY plan_prices_read ON public.plan_prices FOR SELECT TO authenticated USING (true);

CREATE POLICY plan_prices_write ON public.plan_prices TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY plan_public_bullets_read_anon ON public.plan_public_bullets FOR SELECT TO authenticated, anon USING (true);

CREATE POLICY plan_public_bullets_write ON public.plan_public_bullets TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY plan_public_read_anon ON public.plan_public FOR SELECT TO authenticated, anon USING (true);

CREATE POLICY plan_public_write ON public.plan_public TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY plans_read_authenticated ON public.plans FOR SELECT TO authenticated USING (true);

CREATE POLICY plans_write_saas_admin ON public.plans TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY "professional_pricing: owner full access" ON public.professional_pricing USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY "professional_pricing: tenant_admin read" ON public.professional_pricing FOR SELECT TO authenticated USING ((tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND (tm.role = ANY (ARRAY['tenant_admin'::text, 'admin'::text, 'owner'::text]))))));

CREATE POLICY profiles_insert_own ON public.profiles FOR INSERT TO authenticated WITH CHECK ((id = auth.uid()));

CREATE POLICY profiles_read_saas_admin ON public.profiles FOR SELECT USING (public.is_saas_admin());

CREATE POLICY profiles_select_own ON public.profiles FOR SELECT USING ((id = auth.uid()));

CREATE POLICY profiles_update_own ON public.profiles FOR UPDATE USING ((id = auth.uid())) WITH CHECK ((id = auth.uid()));

CREATE POLICY psa_read_saas_admin ON public.public_submission_attempts FOR SELECT TO authenticated USING (public.is_saas_admin());

CREATE POLICY "psc: owner full access" ON public.patient_support_contacts USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY psh_insert ON public.patient_status_history FOR INSERT WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text)));

CREATE POLICY psh_select ON public.patient_status_history FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.view'::text)));

CREATE POLICY pt_insert ON public.patient_timeline FOR INSERT WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.edit'::text)));

CREATE POLICY pt_select ON public.patient_timeline FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'patients.view'::text)));

CREATE POLICY public_read ON public.login_carousel_slides FOR SELECT USING ((ativo = true));

CREATE POLICY recurrence_exceptions_tenant ON public.recurrence_exceptions TO authenticated USING ((tenant_id IN ( SELECT tenant_members.tenant_id
   FROM public.tenant_members
  WHERE (tenant_members.user_id = auth.uid())))) WITH CHECK ((tenant_id IN ( SELECT tenant_members.tenant_id
   FROM public.tenant_members
  WHERE (tenant_members.user_id = auth.uid()))));

CREATE POLICY "recurrence_rule_services: clinic read" ON public.recurrence_rule_services FOR SELECT USING ((EXISTS ( SELECT 1
   FROM public.recurrence_rules r
  WHERE ((r.id = recurrence_rule_services.rule_id) AND public.is_clinic_tenant(r.tenant_id) AND public.is_tenant_member(r.tenant_id) AND public.tenant_has_feature(r.tenant_id, 'agenda.view'::text)))));

CREATE POLICY "recurrence_rule_services: clinic write" ON public.recurrence_rule_services USING ((EXISTS ( SELECT 1
   FROM public.recurrence_rules r
  WHERE ((r.id = recurrence_rule_services.rule_id) AND public.is_clinic_tenant(r.tenant_id) AND public.is_tenant_member(r.tenant_id) AND public.tenant_has_feature(r.tenant_id, 'agenda.edit'::text))))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.recurrence_rules r
  WHERE ((r.id = recurrence_rule_services.rule_id) AND public.is_clinic_tenant(r.tenant_id) AND public.is_tenant_member(r.tenant_id) AND public.tenant_has_feature(r.tenant_id, 'agenda.edit'::text)))));

CREATE POLICY "recurrence_rule_services: owner full access" ON public.recurrence_rule_services TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.recurrence_rules r
  WHERE ((r.id = recurrence_rule_services.rule_id) AND (r.owner_id = auth.uid()))))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.recurrence_rules r
  WHERE ((r.id = recurrence_rule_services.rule_id) AND (r.owner_id = auth.uid())))));

CREATE POLICY recurrence_rules_clinic_read ON public.recurrence_rules FOR SELECT USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.view'::text)));

CREATE POLICY recurrence_rules_clinic_write ON public.recurrence_rules USING ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text))) WITH CHECK ((public.is_clinic_tenant(tenant_id) AND public.is_tenant_member(tenant_id) AND public.tenant_has_feature(tenant_id, 'agenda.edit'::text)));

CREATE POLICY recurrence_rules_owner ON public.recurrence_rules TO authenticated USING ((owner_id = auth.uid())) WITH CHECK ((owner_id = auth.uid()));

CREATE POLICY "reminder_logs: tenant members select" ON public.session_reminder_logs FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = session_reminder_logs.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "reminder_settings: tenant members all" ON public.session_reminder_settings TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = session_reminder_settings.tenant_id) AND (tm.status = 'active'::text)))))) WITH CHECK ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = session_reminder_settings.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "saas_admin can read subscription_intents" ON public.subscription_intents_legacy FOR SELECT TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.saas_admins a
  WHERE (a.user_id = auth.uid()))));

CREATE POLICY "saas_admin can update subscription_intents" ON public.subscription_intents_legacy FOR UPDATE TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.saas_admins a
  WHERE (a.user_id = auth.uid())))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.saas_admins a
  WHERE (a.user_id = auth.uid()))));

CREATE POLICY saas_admin_full ON public.login_carousel_slides USING ((EXISTS ( SELECT 1
   FROM public.profiles
  WHERE ((profiles.id = auth.uid()) AND (profiles.role = 'saas_admin'::text)))));

CREATE POLICY saas_admin_full_access ON public.saas_docs TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.saas_admins
  WHERE (saas_admins.user_id = auth.uid())))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.saas_admins
  WHERE (saas_admins.user_id = auth.uid()))));

CREATE POLICY saas_admins_select_self ON public.saas_admins FOR SELECT TO authenticated USING ((user_id = auth.uid()));

CREATE POLICY saas_security_config_read ON public.saas_security_config FOR SELECT TO authenticated USING (true);

CREATE POLICY saas_security_config_write ON public.saas_security_config FOR UPDATE TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY saas_twilio_config_read ON public.saas_twilio_config FOR SELECT TO authenticated USING (public.is_saas_admin());

CREATE POLICY "select own" ON public.agenda_bloqueios FOR SELECT USING ((owner_id = auth.uid()));

CREATE POLICY service_role_manage_usage ON public.twilio_subaccount_usage USING ((auth.role() = 'service_role'::text));

CREATE POLICY "services: delete" ON public.services FOR DELETE TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY "services: insert" ON public.services FOR INSERT TO authenticated WITH CHECK (((owner_id = auth.uid()) AND (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "services: select" ON public.services FOR SELECT TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "services: update" ON public.services FOR UPDATE TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin())) WITH CHECK (((owner_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY "sla_breaches: select membros/admin" ON public.conversation_sla_breaches FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = conversation_sla_breaches.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "sla_breaches: write service_role" ON public.conversation_sla_breaches TO service_role USING (true) WITH CHECK (true);

CREATE POLICY "sla_rules: select membros/admin" ON public.conversation_sla_rules FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = conversation_sla_rules.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "sla_rules: write admins" ON public.conversation_sla_rules TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = conversation_sla_rules.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.role = ANY (ARRAY['clinic_admin'::text, 'tenant_admin'::text])) AND (tm.status = 'active'::text)))))) WITH CHECK ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = conversation_sla_rules.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.role = ANY (ARRAY['clinic_admin'::text, 'tenant_admin'::text])) AND (tm.status = 'active'::text))))));

CREATE POLICY srl_read_saas_admin ON public.submission_rate_limits FOR SELECT TO authenticated USING (public.is_saas_admin());

CREATE POLICY subscription_events_read_saas ON public.subscription_events FOR SELECT USING (public.is_saas_admin());

CREATE POLICY subscription_events_write_saas ON public.subscription_events FOR INSERT WITH CHECK (public.is_saas_admin());

CREATE POLICY subscription_intents_insert_own ON public.subscription_intents_legacy FOR INSERT TO authenticated WITH CHECK ((user_id = auth.uid()));

CREATE POLICY subscription_intents_personal_owner ON public.subscription_intents_personal TO authenticated USING (((user_id = auth.uid()) OR public.is_saas_admin())) WITH CHECK (((user_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY subscription_intents_select_own ON public.subscription_intents_legacy FOR SELECT TO authenticated USING ((user_id = auth.uid()));

CREATE POLICY subscription_intents_tenant_member ON public.subscription_intents_tenant TO authenticated USING ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND (tm.role = ANY (ARRAY['tenant_admin'::text, 'admin'::text]))))))) WITH CHECK ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND (tm.role = ANY (ARRAY['tenant_admin'::text, 'admin'::text])))))));

CREATE POLICY "subscriptions: read if linked owner_users" ON public.subscriptions FOR SELECT TO authenticated USING ((EXISTS ( SELECT 1
   FROM public.owner_users ou
  WHERE ((ou.owner_id = subscriptions.user_id) AND (ou.user_id = auth.uid())))));

CREATE POLICY subscriptions_insert_own_personal ON public.subscriptions FOR INSERT TO authenticated WITH CHECK (((user_id = auth.uid()) AND (tenant_id IS NULL)));

CREATE POLICY subscriptions_read_own ON public.subscriptions FOR SELECT TO authenticated USING (((user_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY subscriptions_select_for_tenant_members ON public.subscriptions FOR SELECT TO authenticated USING (((tenant_id IS NOT NULL) AND (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = subscriptions.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY subscriptions_update_only_saas_admin ON public.subscriptions FOR UPDATE TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY support_sessions_saas_delete ON public.support_sessions FOR DELETE USING (((auth.uid() = admin_id) AND (EXISTS ( SELECT 1
   FROM public.profiles
  WHERE ((profiles.id = auth.uid()) AND (profiles.role = 'saas_admin'::text))))));

CREATE POLICY support_sessions_saas_insert ON public.support_sessions FOR INSERT TO authenticated WITH CHECK (((admin_id = auth.uid()) AND (EXISTS ( SELECT 1
   FROM public.saas_admins sa
  WHERE (sa.user_id = auth.uid())))));

CREATE POLICY support_sessions_saas_select ON public.support_sessions FOR SELECT USING (((auth.uid() = admin_id) AND (EXISTS ( SELECT 1
   FROM public.profiles
  WHERE ((profiles.id = auth.uid()) AND (profiles.role = 'saas_admin'::text))))));

CREATE POLICY tenant_feature_exceptions_log_read ON public.tenant_feature_exceptions_log FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY tenant_features_select ON public.tenant_features FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY tenant_features_write_saas_only ON public.tenant_features TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY tenant_invites_delete ON public.tenant_invites FOR DELETE TO authenticated USING ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND (tm.role = ANY (ARRAY['tenant_admin'::text, 'admin'::text, 'owner'::text])))))));

CREATE POLICY tenant_invites_insert ON public.tenant_invites FOR INSERT TO authenticated WITH CHECK (((invited_by = auth.uid()) AND (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND (tm.role = ANY (ARRAY['tenant_admin'::text, 'admin'::text, 'owner'::text])))))));

CREATE POLICY tenant_invites_select ON public.tenant_invites FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND (tm.role = ANY (ARRAY['tenant_admin'::text, 'admin'::text, 'owner'::text])))))));

CREATE POLICY tenant_invites_update ON public.tenant_invites FOR UPDATE TO authenticated USING ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND (tm.role = ANY (ARRAY['tenant_admin'::text, 'admin'::text, 'owner'::text]))))))) WITH CHECK ((public.is_saas_admin() OR (tenant_id IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND (tm.role = ANY (ARRAY['tenant_admin'::text, 'admin'::text, 'owner'::text])))))));

CREATE POLICY tenant_members_write_saas ON public.tenant_members TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY tenant_modules_read_own ON public.tenant_modules FOR SELECT TO authenticated USING (((owner_id = auth.uid()) OR public.is_saas_admin()));

CREATE POLICY tenant_modules_write_saas ON public.tenant_modules TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY tenant_select_own_usage ON public.twilio_subaccount_usage FOR SELECT USING ((tenant_id IN ( SELECT tenant_members.tenant_id
   FROM public.tenant_members
  WHERE (tenant_members.user_id = auth.uid()))));

CREATE POLICY tenants_read_members ON public.tenants FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = tenants.id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY tenants_write_saas ON public.tenants TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY therapist_payout_records_self ON public.therapist_payout_records USING ((EXISTS ( SELECT 1
   FROM public.therapist_payouts tp
  WHERE ((tp.id = therapist_payout_records.payout_id) AND (tp.owner_id = auth.uid()))))) WITH CHECK ((EXISTS ( SELECT 1
   FROM public.therapist_payouts tp
  WHERE ((tp.id = therapist_payout_records.payout_id) AND (tp.owner_id = auth.uid())))));

CREATE POLICY therapist_payout_records_tenant_admin ON public.therapist_payout_records FOR SELECT USING ((EXISTS ( SELECT 1
   FROM public.therapist_payouts tp
  WHERE ((tp.id = therapist_payout_records.payout_id) AND public.is_tenant_admin(tp.tenant_id)))));

CREATE POLICY therapist_payouts_self ON public.therapist_payouts USING ((auth.uid() = owner_id)) WITH CHECK ((auth.uid() = owner_id));

CREATE POLICY therapist_payouts_tenant_admin ON public.therapist_payouts FOR SELECT USING (((tenant_id IS NOT NULL) AND public.is_tenant_admin(tenant_id)));

CREATE POLICY tm_select_admin_all_members ON public.tenant_members FOR SELECT TO authenticated USING (public.is_tenant_admin(tenant_id));

CREATE POLICY tm_select_own_membership ON public.tenant_members FOR SELECT TO authenticated USING ((user_id = auth.uid()));

CREATE POLICY "update own" ON public.agenda_bloqueios FOR UPDATE USING ((owner_id = auth.uid()));

CREATE POLICY user_settings_insert_own ON public.user_settings FOR INSERT TO authenticated WITH CHECK ((user_id = auth.uid()));

CREATE POLICY user_settings_select_own ON public.user_settings FOR SELECT USING ((user_id = auth.uid()));

CREATE POLICY user_settings_update_own ON public.user_settings FOR UPDATE USING ((user_id = auth.uid())) WITH CHECK ((user_id = auth.uid()));

CREATE POLICY users_read_usuario_docs ON public.saas_docs FOR SELECT TO authenticated USING (((ativo = true) AND (tipo_acesso = 'usuario'::text)));

CREATE POLICY votos_select_own ON public.saas_doc_votos FOR SELECT TO authenticated USING ((user_id = auth.uid()));

CREATE POLICY votos_upsert_own ON public.saas_doc_votos TO authenticated USING ((user_id = auth.uid())) WITH CHECK ((user_id = auth.uid()));

CREATE POLICY "wa_credits_balance: select tenant" ON public.whatsapp_credits_balance FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = whatsapp_credits_balance.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "wa_credits_balance: update tenant" ON public.whatsapp_credits_balance FOR UPDATE TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = whatsapp_credits_balance.tenant_id) AND (tm.status = 'active'::text)))))) WITH CHECK ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = whatsapp_credits_balance.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "wa_credits_tx: select tenant" ON public.whatsapp_credits_transactions FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = whatsapp_credits_transactions.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "wa_incidents: select membros/admin" ON public.whatsapp_connection_incidents FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.tenant_id = whatsapp_connection_incidents.tenant_id) AND (tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "wa_incidents: write service_role" ON public.whatsapp_connection_incidents TO service_role USING (true) WITH CHECK (true);

CREATE POLICY "wa_packages: manage saas admin" ON public.whatsapp_credit_packages TO authenticated USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

CREATE POLICY "wa_packages: select active" ON public.whatsapp_credit_packages FOR SELECT TO authenticated USING (((is_active = true) OR public.is_saas_admin()));

CREATE POLICY "wa_purchases: select tenant" ON public.whatsapp_credit_purchases FOR SELECT TO authenticated USING ((public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.tenant_id = whatsapp_credit_purchases.tenant_id) AND (tm.status = 'active'::text))))));

CREATE POLICY "Allow authenticated updates" ON storage.objects FOR UPDATE TO authenticated USING ((bucket_id = ANY (ARRAY['avatars'::text, 'logos'::text])));

CREATE POLICY "Allow authenticated uploads" ON storage.objects FOR INSERT TO authenticated WITH CHECK ((bucket_id = ANY (ARRAY['avatars'::text, 'logos'::text])));

CREATE POLICY "Public read" ON storage.objects FOR SELECT USING ((bucket_id = ANY (ARRAY['avatars'::text, 'logos'::text])));

CREATE POLICY agendador_storage_owner_delete ON storage.objects FOR DELETE TO authenticated USING (((bucket_id = 'agendador'::text) AND ((storage.foldername(name))[1] = (auth.uid())::text)));

CREATE POLICY agendador_storage_owner_insert ON storage.objects FOR INSERT TO authenticated WITH CHECK (((bucket_id = 'agendador'::text) AND ((storage.foldername(name))[1] = (auth.uid())::text)));

CREATE POLICY agendador_storage_owner_update ON storage.objects FOR UPDATE TO authenticated USING (((bucket_id = 'agendador'::text) AND ((storage.foldername(name))[1] = (auth.uid())::text)));

CREATE POLICY agendador_storage_public_read ON storage.objects FOR SELECT USING ((bucket_id = 'agendador'::text));

CREATE POLICY "avatars authenticated upload" ON storage.objects FOR INSERT WITH CHECK (((bucket_id = 'avatars'::text) AND (auth.role() = 'authenticated'::text) AND ((storage.foldername(name))[1] = (auth.uid())::text)));

CREATE POLICY "avatars owner delete" ON storage.objects FOR DELETE USING (((bucket_id = 'avatars'::text) AND ((storage.foldername(name))[1] = (auth.uid())::text)));

CREATE POLICY "avatars owner update" ON storage.objects FOR UPDATE USING (((bucket_id = 'avatars'::text) AND ((storage.foldername(name))[1] = (auth.uid())::text)));

CREATE POLICY "avatars public read" ON storage.objects FOR SELECT USING ((bucket_id = 'avatars'::text));

CREATE POLICY avatars_delete_own ON storage.objects FOR DELETE TO authenticated USING (((bucket_id = 'avatars'::text) AND (name ~~ ((auth.uid())::text || '/%'::text))));

CREATE POLICY avatars_delete_own_folder ON storage.objects FOR DELETE USING (((bucket_id = 'avatars'::text) AND (auth.role() = 'authenticated'::text) AND (name ~~ (('owners/'::text || auth.uid()) || '/%'::text))));

CREATE POLICY avatars_insert_own ON storage.objects FOR INSERT TO authenticated WITH CHECK (((bucket_id = 'avatars'::text) AND (name ~~ ((auth.uid())::text || '/%'::text))));

CREATE POLICY avatars_insert_own_folder ON storage.objects FOR INSERT WITH CHECK (((bucket_id = 'avatars'::text) AND (auth.role() = 'authenticated'::text) AND (name ~~ (('owners/'::text || auth.uid()) || '/%'::text))));

CREATE POLICY avatars_read ON storage.objects FOR SELECT USING ((bucket_id = 'avatars'::text));

CREATE POLICY avatars_select_own ON storage.objects FOR SELECT TO authenticated USING (((bucket_id = 'avatars'::text) AND (name ~~ ((auth.uid())::text || '/%'::text))));

CREATE POLICY avatars_update_own ON storage.objects FOR UPDATE TO authenticated USING (((bucket_id = 'avatars'::text) AND (name ~~ ((auth.uid())::text || '/%'::text)))) WITH CHECK (((bucket_id = 'avatars'::text) AND (name ~~ ((auth.uid())::text || '/%'::text))));

CREATE POLICY avatars_update_own_folder ON storage.objects FOR UPDATE USING (((bucket_id = 'avatars'::text) AND (auth.role() = 'authenticated'::text) AND (name ~~ (('owners/'::text || auth.uid()) || '/%'::text)))) WITH CHECK (((bucket_id = 'avatars'::text) AND (auth.role() = 'authenticated'::text) AND (name ~~ (('owners/'::text || auth.uid()) || '/%'::text))));

CREATE POLICY "documents: tenant member delete" ON storage.objects FOR DELETE TO authenticated USING (((bucket_id = 'documents'::text) AND (public.is_saas_admin() OR (((storage.foldername(name))[1])::uuid IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))))));

CREATE POLICY "documents: tenant member read" ON storage.objects FOR SELECT TO authenticated USING (((bucket_id = 'documents'::text) AND (public.is_saas_admin() OR (((storage.foldername(name))[1])::uuid IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))))));

CREATE POLICY "documents: tenant member upload" ON storage.objects FOR INSERT TO authenticated WITH CHECK (((bucket_id = 'documents'::text) AND (((storage.foldername(name))[1])::uuid IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY "generated-docs: tenant member delete" ON storage.objects FOR DELETE TO authenticated USING (((bucket_id = 'generated-docs'::text) AND (public.is_saas_admin() OR (((storage.foldername(name))[1])::uuid IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))))));

CREATE POLICY "generated-docs: tenant member read" ON storage.objects FOR SELECT TO authenticated USING (((bucket_id = 'generated-docs'::text) AND (public.is_saas_admin() OR (((storage.foldername(name))[1])::uuid IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text)))))));

CREATE POLICY "generated-docs: tenant member upload" ON storage.objects FOR INSERT TO authenticated WITH CHECK (((bucket_id = 'generated-docs'::text) AND (((storage.foldername(name))[1])::uuid IN ( SELECT tm.tenant_id
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text))))));

CREATE POLICY intake_read_owner_only ON storage.objects FOR SELECT TO authenticated USING (((bucket_id = 'avatars'::text) AND ((storage.foldername(name))[1] = 'intakes'::text)));

CREATE POLICY public_read ON storage.objects FOR SELECT USING ((bucket_id = 'saas-docs'::text));

CREATE POLICY saas_admin_delete ON storage.objects FOR DELETE TO authenticated USING (((bucket_id = 'saas-docs'::text) AND (EXISTS ( SELECT 1
   FROM public.saas_admins
  WHERE (saas_admins.user_id = auth.uid())))));

CREATE POLICY saas_admin_upload ON storage.objects FOR INSERT TO authenticated WITH CHECK (((bucket_id = 'saas-docs'::text) AND (EXISTS ( SELECT 1
   FROM public.saas_admins
  WHERE (saas_admins.user_id = auth.uid())))));

CREATE POLICY "whatsapp-media: delete saas admin" ON storage.objects FOR DELETE TO authenticated USING (((bucket_id = 'whatsapp-media'::text) AND public.is_saas_admin()));

CREATE POLICY "whatsapp-media: read tenant members" ON storage.objects FOR SELECT TO authenticated USING (((bucket_id = 'whatsapp-media'::text) AND (public.is_saas_admin() OR (EXISTS ( SELECT 1
   FROM public.tenant_members tm
  WHERE ((tm.user_id = auth.uid()) AND (tm.status = 'active'::text) AND ((storage.foldername(objects.name))[1] = (tm.tenant_id)::text)))))));
