-- Migration 015 — Credenciales WhatsApp por tenant
-- Reemplaza tenants.meta_phone_number_id por una tabla dedicada.
-- El access_token se guarda cifrado (AES-256-GCM via TokenCrypto), nunca en texto plano.

CREATE TABLE IF NOT EXISTS tenant_whatsapp (
    id             BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    tenant_id      BIGINT UNSIGNED NOT NULL,
    provider       ENUM('meta','twilio') NOT NULL DEFAULT 'meta',
    phone_number_id VARCHAR(64) NOT NULL,
    waba_id        VARCHAR(64) NULL,
    access_token   TEXT NULL,          -- cifrado con AES-256-GCM, nunca en claro
    status         ENUM('active','inactive','suspended') NOT NULL DEFAULT 'active',
    created_at     TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at     TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uq_twp_phone (phone_number_id),
    INDEX idx_twp_tenant (tenant_id),
    CONSTRAINT fk_twp_tenant
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
