-- Migration 002 — Web chat channel + Vale Admin (super-admin)
-- Applies on top of SCHEMA.sql (Sprint 1). Safe to run once.

-- Track A: web channel needs a non-secret embed key per tenant.
ALTER TABLE tenants
    ADD COLUMN web_public_key CHAR(32) NULL AFTER whatsapp_number,
    ADD UNIQUE KEY uq_tenants_web_public_key (web_public_key);



-- Track B: super-admin lives in its own table (crosses tenants on purpose),
-- separate from users to never contaminate tenant scoping.
CREATE TABLE IF NOT EXISTS admins (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(160) NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    name VARCHAR(120) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uq_admins_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Backfill a web_public_key for existing tenants (32 hex chars).
-- Portable across MySQL 8 and MariaDB (no RANDOM_BYTES dependency):
-- UUID() + RAND() make each row unique; SHA2 -> hex; LEFT(...,32) fits CHAR(32).
UPDATE tenants
SET web_public_key = LEFT(SHA2(CONCAT(id, UUID(), RAND()), 256), 32)
WHERE web_public_key IS NULL;
