USE whp;

-- =====================================================================
-- Bichon paid email archival addon
-- =====================================================================
-- Adds:
--   1. client_allowances.max_archived_mailboxes
--      Per-customer entitlement: number of mailboxes the customer is
--      allowed to enable Bichon archival for.
--   2. email_accounts.archival_enabled / bichon_account_id /
--      archival_enabled_at / archival_paused_at / archival_last_error
--      Per-mailbox archival state and the remote Bichon account id
--      returned by POST /api/v1/account.
--   3. email_archival_events
--      Audit log of every state transition (enabled, disabled, paused,
--      resumed, failed, deleted) so support and WHMCS billing reconciles
--      can be replayed.
--
-- Idempotent: ADD COLUMN IF NOT EXISTS / CREATE TABLE IF NOT EXISTS
-- so re-running this migration is safe.
-- =====================================================================

-- 1. Per-customer Bichon entitlement
ALTER TABLE client_allowances
    ADD COLUMN IF NOT EXISTS max_archived_mailboxes INT NOT NULL DEFAULT 0
        COMMENT 'Per-customer Bichon archival mailbox slots';

-- 2. Per-mailbox archival flags / remote id / lifecycle timestamps
ALTER TABLE email_accounts
    ADD COLUMN IF NOT EXISTS archival_enabled TINYINT(1) NOT NULL DEFAULT 0,
    ADD COLUMN IF NOT EXISTS bichon_account_id VARCHAR(64) DEFAULT NULL
        COMMENT 'Account ID returned by Bichon POST /api/v1/account',
    ADD COLUMN IF NOT EXISTS archival_enabled_at TIMESTAMP NULL DEFAULT NULL,
    ADD COLUMN IF NOT EXISTS archival_paused_at TIMESTAMP NULL DEFAULT NULL,
    ADD COLUMN IF NOT EXISTS archival_last_error VARCHAR(255) DEFAULT NULL;

-- 3. Audit log
CREATE TABLE IF NOT EXISTS email_archival_events (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email_account_id  INT NOT NULL,
    username          VARCHAR(32) NOT NULL,
    event_type        ENUM('enabled','disabled','paused','resumed','failed','deleted') NOT NULL,
    bichon_account_id VARCHAR(64) DEFAULT NULL,
    actor             VARCHAR(32) NOT NULL COMMENT 'username, "root", or "whmcs"',
    details           TEXT DEFAULT NULL,
    created_at        TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_email_account (email_account_id),
    INDEX idx_username_created (username, created_at),
    INDEX idx_event_type (event_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
