{
  "container": "supabase_db_agenciapsi-primesakai",
  "database": "postgres",
  "user": "postgres",
  "backupRetentionDays": 30,
  "schema": "schema/00_full/schema.sql",
  "migrationsDir": "migrations",
  "seedsDir": "seeds",
  "fixesDir": "fixes",
  "seeds": {
    "users": [
      "seed_001_fixed.sql",
      "seed_002.sql",
      "seed_003.sql"
    ],
    "system": [
      "seed_010_plans.sql",
      "seed_011_features.sql",
      "seed_012_plan_features.sql",
      "seed_013_subscriptions.sql",
      "seed_014_global_data.sql",
      "seed_015_document_templates.sql",
      "seed_030_dev_phases_items.sql",
      "seed_031_dev_auditoria.sql",
      "seed_032_dev_competitors.sql",
      "seed_040_clinical_note_templates.sql",
      "seed_050_specialties.sql",
      "seed_060_consent_forms_extra.sql"
    ],
    "test_data": [
      "seed_020_test_data.sql"
    ]
  },
  "fixes": [
    "fix_addon_credits_fk.sql",
    "fix_addon_rls_saas_admin.sql",
    "fix_missing_subscriptions.sql",
    "fix_notification_templates_rls_admin.sql",
    "fix_seed_patient_groups.sql",
    "fix_subscriptions_validate_scope.sql",
    "fix_template_keys_match_populate.sql",
    "fix_encoding_accents.sql"
  ],
  "verify": {
    "tables": [
      { "name": "auth.users",                 "min": 1 },
      { "name": "profiles",                   "min": 1 },
      { "name": "tenants",                    "min": 1 },
      { "name": "plans",                      "min": 7 },
      { "name": "features",                   "min": 20 },
      { "name": "plan_features",              "min": 50 },
      { "name": "subscriptions",              "min": 1 },
      { "name": "email_templates_global",     "min": 10 },
      { "name": "notification_templates",     "min": 5 },
      { "name": "document_templates",         "min": 1 }
    ],
    "views": [
      "v_tenant_entitlements",
      "v_tenant_active_subscription"
    ]
  },
  "status": {
    "tables": [
      "auth.users",
      "profiles",
      "tenants",
      "tenant_members",
      "plans",
      "features",
      "plan_features",
      "subscriptions",
      "patients",
      "agenda_eventos",
      "services",
      "financial_records",
      "document_templates",
      "documents",
      "email_templates_global",
      "notification_templates"
    ]
  },
  "domains": {
    "SaaS / Planos": [
      "plans", "plan_features", "plan_prices", "plan_public", "plan_public_bullets",
      "features", "modules", "module_features",
      "subscriptions", "subscription_events",
      "subscription_intents_legacy", "subscription_intents_personal", "subscription_intents_tenant",
      "tenant_modules", "tenant_features", "tenant_feature_exceptions_log",
      "billing_contracts", "entitlements_invalidation"
    ],
    "Addons / Créditos": [
      "addon_products", "addon_credits", "addon_transactions",
      "whatsapp_credits_balance", "whatsapp_credits_transactions",
      "whatsapp_credit_packages", "whatsapp_credit_purchases"
    ],
    "Tenants / Multi-tenant": [
      "tenants", "profiles", "user_settings",
      "tenant_invites", "tenant_members",
      "company_profiles", "support_sessions",
      "saas_admins", "owner_users", "dev_user_credentials"
    ],
    "Pacientes": [
      "patients", "patient_contacts", "patient_support_contacts",
      "patient_groups", "patient_group_patient",
      "patient_tags", "patient_patient_tag",
      "patient_discounts", "patient_intake_requests", "patient_invites",
      "patient_status_history", "patient_timeline",
      "contact_types", "contact_phones",
      "contact_email_types", "contact_emails"
    ],
    "Agenda / Agendamento": [
      "agenda_eventos", "agenda_bloqueios", "agenda_configuracoes",
      "agenda_online_slots", "agenda_regras_semanais",
      "agenda_slots_bloqueados_semanais", "agenda_slots_regras",
      "agendador_configuracoes", "agendador_solicitacoes"
    ],
    "Financeiro": [
      "financial_categories", "financial_exceptions", "financial_records",
      "payment_settings", "professional_pricing",
      "therapist_payouts", "therapist_payout_records",
      "recurrence_rules", "recurrence_exceptions", "recurrence_rule_services"
    ],
    "Serviços / Prontuários": [
      "services", "commitment_services", "commitment_time_logs",
      "determined_commitments", "determined_commitment_fields",
      "insurance_plans", "insurance_plan_services",
      "medicos"
    ],
    "Documentos": [
      "documents", "document_templates", "document_generated",
      "document_access_logs", "document_share_links", "document_signatures"
    ],
    "Comunicação / Notificações": [
      "email_templates_global", "email_templates_tenant", "email_layout_config",
      "notification_templates", "notification_channels", "notification_preferences",
      "notification_logs", "notification_schedules", "notification_queue",
      "notifications", "notice_dismissals", "global_notices", "login_carousel_slides",
      "twilio_subaccount_usage", "saas_twilio_config"
    ],
    "CRM Conversas (WhatsApp)": [
      "conversation_messages", "conversation_threads",
      "conversation_notes",
      "conversation_tags", "conversation_thread_tags",
      "conversation_optouts", "conversation_optout_keywords",
      "conversation_autoreply_settings", "conversation_autoreply_log",
      "session_reminder_settings", "session_reminder_logs",
      "conversation_assignments",
      "conversation_bots", "conversation_bot_sessions",
      "conversation_sla_rules", "conversation_sla_breaches",
      "whatsapp_connection_incidents"
    ],
    "Segurança / Auditoria": [
      "submission_rate_limits",
      "audit_logs",
      "saas_security_config",
      "math_challenges",
      "patient_invite_attempts",
      "public_submission_attempts"
    ],
    "Central SaaS (docs/FAQ)": [
      "saas_docs", "saas_doc_votos", "saas_faq", "saas_faq_itens"
    ],
    "Dev / Tracking": [
      "dev_auditoria_items", "dev_verificacoes_items", "dev_test_items",
      "dev_roadmap_phases", "dev_roadmap_items",
      "dev_competitors", "dev_competitor_features",
      "dev_comparison_matrix", "dev_comparison_competitor_status",
      "dev_generation_log"
    ],
    "Estrutura / Calendário": [
      "feriados"
    ]
  },
  "domainColors": {
    "SaaS / Planos":                  "#4f8cff",
    "Addons / Créditos":              "#a78bfa",
    "Tenants / Multi-tenant":         "#6ee7b7",
    "Pacientes":                      "#f472b6",
    "Agenda / Agendamento":           "#38bdf8",
    "Financeiro":                     "#f87171",
    "Serviços / Prontuários":         "#34d399",
    "Documentos":                     "#0ea5e9",
    "Comunicação / Notificações":     "#fbbf24",
    "CRM Conversas (WhatsApp)":       "#25d366",
    "Segurança / Auditoria":          "#ef4444",
    "Central SaaS (docs/FAQ)":        "#c084fc",
    "Dev / Tracking":                 "#94a3b8",
    "Estrutura / Calendário":         "#fb923c"
  },
  "infrastructure": {
    "Banco & Backend": {
      "color": "#4f8cff",
      "items": [
        {
          "name": "Supabase",
          "role": "Postgres + Auth + Storage + Realtime + Edge Functions",
          "env": "Local (Docker) + Cloud",
          "status": "ativo",
          "notes": "Stack principal. Migrations em database-novo/migrations/. Functions em supabase/functions/. CLI via npx supabase."
        },
        {
          "name": "PostgreSQL 15",
          "role": "Banco de dados relacional (via container supabase_db_agenciapsi-primesakai)",
          "env": "Local (Docker)",
          "status": "ativo",
          "notes": "RLS habilitada em todas as tabelas públicas. Multi-tenant via tenant_id. SECURITY DEFINER em RPCs sensíveis."
        },
        {
          "name": "Docker + Docker Compose",
          "role": "Orquestração dos containers do stack Supabase local + Evolution API",
          "env": "Local",
          "status": "ativo",
          "notes": "docker-compose.yml na raiz. Iniciado via npx supabase start."
        }
      ]
    },
    "Email": {
      "color": "#fbbf24",
      "items": [
        {
          "name": "Mailpit (Supabase inbucket)",
          "role": "Inbox SMTP local para capturar emails de teste",
          "env": "Local (Docker)",
          "status": "ativo",
          "notes": "Container supabase_inbucket. Usado em dev para validar templates sem enviar email real."
        },
        {
          "name": "SMTP produção",
          "role": "Envio real de emails transacionais (faturas, convites, notificações)",
          "env": "Cloud (pendente)",
          "status": "pendente",
          "notes": "Requer SMTP_HOST/PORT/USER/PASS/FROM nos secrets das edge functions."
        }
      ]
    },
    "WhatsApp / SMS": {
      "color": "#34d399",
      "items": [
        {
          "name": "Evolution API",
          "role": "WhatsApp self-hosted via Baileys (tier gratuito do SaaS — 'WhatsApp Pessoal')",
          "env": "Local (Docker)",
          "status": "ativo",
          "notes": "Container via evolution-api/docker-compose.yml. Uso do usuário conecta via QR code no celular real. Sem SLA, Meta pode banir número. Envio sem custo. Edge functions: evolution-whatsapp-inbound, evolution-webhook-provision, send-whatsapp-message."
        },
        {
          "name": "Twilio WhatsApp Business API",
          "role": "WhatsApp oficial (tier pago rebrandeado como 'WhatsApp Oficial AgenciaPSI')",
          "env": "Cloud",
          "status": "ativo",
          "notes": "API oficial Meta, zero risco de ban. Credenciais em notification_channels (twilio_subaccount_sid + credentials.subaccount_auth_token). Envio consome 1 crédito via RPC deduct_whatsapp_credits (atômico + rollback em falha). Provisionamento: supabase/functions/twilio-whatsapp-provision/."
        }
      ]
    },
    "Pagamentos / Billing": {
      "color": "#fb923c",
      "items": [
        {
          "name": "Asaas (gateway PIX/cartão/boleto)",
          "role": "Processamento de pagamentos pra compra de créditos WhatsApp (Marco B)",
          "env": "Cloud — sandbox.asaas.com em dev, api.asaas.com em prod",
          "status": "ativo",
          "notes": "API key em ASAAS_API_KEY (env secret). URL em ASAAS_API_URL. Webhook token opcional em ASAAS_WEBHOOK_TOKEN. Edge functions: create-whatsapp-credit-charge (cria customer + PIX), asaas-webhook (recebe PAYMENT_RECEIVED/CONFIRMED e credita saldo via add_whatsapp_credits)."
        },
        {
          "name": "ngrok (dev only — tunnel pro webhook)",
          "role": "Expõe edge functions locais pra Asaas alcançar via internet",
          "env": "Local (dev)",
          "status": "opcional",
          "notes": "Uso: ngrok http 54321 → copia URL e cadastra em Asaas → Integrações → Webhooks → /functions/v1/asaas-webhook. Necessário só pra testar fluxo completo local incluindo confirmação de pagamento."
        }
      ]
    },
    "Geração de documentos": {
      "color": "#38bdf8",
      "items": [
        {
          "name": "pdfmake 0.3.7",
          "role": "Geração de PDF client-side (atestados, laudos, recibos)",
          "env": "Browser",
          "status": "ativo",
          "notes": "UMD/webpack. Requer optimizeDeps.include explícito no vite.config.mjs."
        },
        {
          "name": "html-to-pdfmake / html2pdf.js / jsPDF",
          "role": "Conversão HTML→PDF para documentos ricos",
          "env": "Browser",
          "status": "ativo",
          "notes": "Usado em document_templates e documents gerados para pacientes."
        },
        {
          "name": "Jodit + Quill",
          "role": "Editores de texto rico para templates de documentos",
          "env": "Browser",
          "status": "ativo",
          "notes": "Jodit em DocumentTemplateEditor; Quill em páginas legadas. Migração em andamento."
        },
        {
          "name": "html2canvas-pro",
          "role": "Captura de screenshots de DOM (preview/export)",
          "env": "Browser",
          "status": "ativo",
          "notes": "Usado para thumbnails de templates e previews."
        }
      ]
    },
    "Frontend": {
      "color": "#a78bfa",
      "items": [
        {
          "name": "Vue 3 + Composition API",
          "role": "Framework principal (script setup)",
          "env": "Browser",
          "status": "ativo",
          "notes": "~487 componentes Vue. Pinia para state management."
        },
        {
          "name": "Vite 5",
          "role": "Build tool e dev server",
          "env": "Node.js",
          "status": "ativo",
          "notes": "vite-plugin-compression (Brotli/Gzip), unplugin-auto-import para PrimeVue e Vue. rollup-plugin-visualizer para análise de bundle."
        },
        {
          "name": "PrimeVue 4 (tema Sakai)",
          "role": "Biblioteca de componentes UI",
          "env": "Browser",
          "status": "ativo",
          "notes": "@primeuix/themes. auto-import-resolver. DataTable, Dialog, DatePicker, Popover, Toast, ConfirmDialog headless."
        },
        {
          "name": "Tailwind CSS v4",
          "role": "Utility-first CSS",
          "env": "Browser",
          "status": "ativo",
          "notes": "@tailwindcss/vite + tailwindcss-primeui. Surface tokens do PrimeVue (var(--surface-card), var(--text-color-secondary))."
        },
        {
          "name": "Vue Router",
          "role": "Roteamento SPA com guards por role/tenant",
          "env": "Browser",
          "status": "ativo",
          "notes": "Grupos de rota: therapist, admin, supervisor, saas, billing, account, configuracoes, features."
        },
        {
          "name": "FullCalendar 6",
          "role": "Calendário para agenda de terapeutas",
          "env": "Browser",
          "status": "ativo",
          "notes": "Plugins: daygrid, timegrid, interaction, list, resource, resource-timegrid."
        },
        {
          "name": "Chart.js 3",
          "role": "Gráficos para dashboards (financeiro, KPIs)",
          "env": "Browser",
          "status": "ativo",
          "notes": "Usado em dashboards do therapist e clinic."
        }
      ]
    },
    "Dev / Tooling": {
      "color": "#94a3b8",
      "items": [
        {
          "name": "Supabase CLI",
          "role": "Gerencia ambiente local, migrations, edge functions",
          "env": "Node.js",
          "status": "ativo",
          "notes": "Via npx supabase. Start/stop/status/db-push/functions-deploy."
        },
        {
          "name": "db.cjs (este projeto)",
          "role": "CLI auxiliar pra setup/backup/restore/migrate/verify via docker exec",
          "env": "Node.js",
          "status": "ativo",
          "notes": "Complementa o supabase CLI com fluxo schema + fixes + seeds + migrations. Encoding UTF-8 preservado."
        },
        {
          "name": "generate-dashboard.cjs",
          "role": "Gera dashboard HTML estático do schema (tabelas, FKs, infra)",
          "env": "Node.js",
          "status": "ativo",
          "notes": "Standalone, sem dependências externas. Lê config de db.config.json e schema do backup mais recente."
        },
        {
          "name": "Vitest 4",
          "role": "Runner de testes unitários",
          "env": "Node.js",
          "status": "ativo",
          "notes": "npm test / test:watch / test:ui. Bateria inicial em src/**/__tests__."
        },
        {
          "name": "ESLint + Prettier",
          "role": "Lint + formatação automática",
          "env": "Node.js",
          "status": "ativo",
          "notes": "@vue/eslint-config-prettier. Rodado via npm run lint."
        }
      ]
    }
  }
}
