<?php

namespace WPSN\Modules\AI;

defined('ABSPATH') || exit;

final class AIInstaller
{
    public const DB_VERSION = '3';

    public static function maybeInstall(): void
    {
        if (!function_exists('dbDelta')) {
            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        }

        $installed = get_option('wpsn_ai_db_version');
        if ($installed === self::DB_VERSION) {
            return;
        }

        global $wpdb;
        $table = $wpdb->prefix . 'wpsn_ai_calls';
        $ledger = $wpdb->prefix . 'wpsn_ai_credits_ledger';
        $charset = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE {$table} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            created_at DATETIME NOT NULL,
            provider VARCHAR(32) NOT NULL,
            model VARCHAR(64) NOT NULL,
            purpose VARCHAR(32) NOT NULL,
            post_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
            prompt_key VARCHAR(64) NOT NULL DEFAULT '',
            prompt_version INT UNSIGNED NOT NULL DEFAULT 1,
            prompt_hash CHAR(40) NOT NULL DEFAULT '',
            tokens_in INT UNSIGNED NOT NULL DEFAULT 0,
            tokens_out INT UNSIGNED NOT NULL DEFAULT 0,
            tokens_total INT UNSIGNED NOT NULL DEFAULT 0,
            cost_usd DECIMAL(10,4) NOT NULL DEFAULT 0.0000,
            latency_ms INT UNSIGNED NOT NULL DEFAULT 0,
            success TINYINT(1) NOT NULL DEFAULT 0,
            error_message TEXT NULL,
            response_text LONGTEXT NULL,
            PRIMARY KEY  (id),
            KEY created_at (created_at),
            KEY post_id (post_id),
            KEY prompt_key (prompt_key),
            KEY success (success)
        ) {$charset};";

        dbDelta($sql);

        // Credits ledger (optional feature; table is safe to create regardless).
        $sql2 = "CREATE TABLE {$ledger} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            created_at DATETIME NOT NULL,
            user_id BIGINT UNSIGNED NULL,
            credits_delta DECIMAL(18,6) NOT NULL DEFAULT 0.000000,
            balance_after DECIMAL(18,6) NOT NULL DEFAULT 0.000000,
            mode VARCHAR(16) NOT NULL DEFAULT 'tokens',
            provider VARCHAR(32) NOT NULL DEFAULT '',
            model VARCHAR(64) NOT NULL DEFAULT '',
            purpose VARCHAR(64) NOT NULL DEFAULT '',
            object_type VARCHAR(20) NOT NULL DEFAULT '',
            object_id BIGINT UNSIGNED NULL,
            tokens_total INT UNSIGNED NOT NULL DEFAULT 0,
            cost_usd DECIMAL(10,4) NOT NULL DEFAULT 0.0000,
            note VARCHAR(255) NOT NULL DEFAULT '',
            meta LONGTEXT NULL,
            PRIMARY KEY  (id),
            KEY created_at (created_at),
            KEY user_id (user_id),
            KEY object_id (object_id),
            KEY purpose (purpose)
        ) {$charset};";

        dbDelta($sql2);

        update_option('wpsn_ai_db_version', self::DB_VERSION, false);
    }
}
