<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /migrations/019_google_connection.php
// Description: Creates amai_google_connection table for Google Business Profile OAuth channel - NUCLEAR+++
// Last Edited: 2026-04-20
// ==================================================

namespace AutoMarketerAI\Migrations;

// No direct access
defined('ABSPATH') || exit;

final class Migration_019_GoogleConnection
{
    // Migration version identifier -- never change once shipped
    public const VERSION = '019';
    public const DESCRIPTION = 'Create amai_google_connection table';

    public function up(): void
    {
        global $wpdb;

        $charset = $wpdb->get_charset_collate();

        // --------------------------------------------------
        // amai_google_connection
        // Stores the connected Google Business Profile account.
        // access_token_enc and refresh_token_enc are AES-256-CBC
        // encrypted via KeyVault before storage.
        // --------------------------------------------------
        $sql = "CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}amai_google_connection` (
            `id`                  BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            `tenant_id`           VARCHAR(64)  NOT NULL DEFAULT 'default',
            `google_account_id`   VARCHAR(128) NOT NULL DEFAULT '',
            `location_id`         VARCHAR(255) NOT NULL DEFAULT '',
            `location_name`       VARCHAR(255) NOT NULL DEFAULT '',
            `business_name`       VARCHAR(255) NOT NULL DEFAULT '',
            `access_token_enc`    TEXT         NOT NULL,
            `refresh_token_enc`   TEXT         NOT NULL,
            `token_expires_at`    DATETIME     NOT NULL,
            `connected_at`        DATETIME     NOT NULL,
            `last_verified_at`    DATETIME     NOT NULL,
            `status`              ENUM('active','expired','error') NOT NULL DEFAULT 'active',
            PRIMARY KEY (`id`),
            UNIQUE KEY `tenant_id` (`tenant_id`)
        ) {$charset};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }
}