<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /migrations/015_tiktok_connection.php
// Description: Creates amai_tiktok_connection table for TikTok OAuth channel - NUCLEAR+++
// Last Edited: 2026-04-15
// ==================================================

namespace AutoMarketerAI\Migrations;

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

final class Migration_015_TikTokConnection
{
    // Migration version identifier - never change once shipped
    public const VERSION = '015';
    public const DESCRIPTION = 'Create amai_tiktok_connection table';

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

        $charset = $wpdb->get_charset_collate();

        // --------------------------------------------------
        // amai_tiktok_connection
        // Stores the connected TikTok creator account.
        // access_token_enc and refresh_token_enc are both
        // AES-256-CBC encrypted at rest via KeyVault.
        // open_id is TikTok's unique user identifier - used
        // as the creator identity on all publish API calls.
        // Access tokens expire after 24 hours - daily cron
        // refreshes using the 365-day refresh token.
        // One row per tenant - same pattern as FB/LI connection.
        // --------------------------------------------------
        $table = $wpdb->prefix . 'amai_tiktok_connection';

        $exists = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s",
                DB_NAME,
                $table
            )
        );

        if ((int) $exists > 0) {
            return;
        }

        $wpdb->query(
            "CREATE TABLE `{$table}` (
                `id`                 bigint unsigned  NOT NULL AUTO_INCREMENT,
                `tenant_id`          varchar(64)      NOT NULL DEFAULT 'default',
                `open_id`            varchar(128)     NOT NULL DEFAULT '',
                `username`           varchar(255)     NOT NULL DEFAULT '',
                `display_name`       varchar(255)     NOT NULL DEFAULT '',
                `avatar_url`         varchar(512)     DEFAULT NULL,
                `followers`          int unsigned     DEFAULT NULL,
                `access_token_enc`   text             NOT NULL,
                `refresh_token_enc`  text             DEFAULT NULL,
                `token_expires_at`   datetime         DEFAULT NULL,
                `refresh_expires_at` datetime         DEFAULT NULL,
                `connected_at`       datetime         NOT NULL DEFAULT CURRENT_TIMESTAMP,
                `last_verified_at`   datetime         DEFAULT NULL,
                `status`             enum('active','expired','revoked','error') NOT NULL DEFAULT 'active',
                `created_at`         datetime         NOT NULL DEFAULT CURRENT_TIMESTAMP,
                `updated_at`         datetime         NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (`id`),
                UNIQUE KEY `uq_tenant` (`tenant_id`),
                KEY `idx_status` (`status`)
            ) {$charset}"
        );
    }

    public function down(): void
    {
        // Forward-only migrations - down() documents intent only.
        // Never call this in production.
        global $wpdb;
        $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}amai_tiktok_connection");
    }
}