<?php

namespace HaoZiTeam\AIPost\Service\Features;

defined('ABSPATH') || exit;

class AdminChatTables
{
    public static function table_sessions(): string
    {
        global $wpdb;
        return $wpdb->prefix . 'ai_post_chat_sessions';
    }

    public static function table_messages(): string
    {
        global $wpdb;
        return $wpdb->prefix . 'ai_post_chat_messages';
    }

    public static function create_tables(): void
    {
        global $wpdb;

        $charset_collate = $wpdb->get_charset_collate();
        $sessions = self::table_sessions();
        $messages = self::table_messages();

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';

        $sql1 = "CREATE TABLE IF NOT EXISTS {$sessions} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            user_id BIGINT UNSIGNED NOT NULL,
            title VARCHAR(255) NOT NULL DEFAULT '',
            model_key VARCHAR(64) NOT NULL DEFAULT '',
            model_name VARCHAR(128) NOT NULL DEFAULT '',
            created_at DATETIME NOT NULL,
            updated_at DATETIME NOT NULL,
            deleted_at DATETIME NULL,
            PRIMARY KEY (id),
            KEY idx_user_updated (user_id, updated_at),
            KEY idx_user_title (user_id, title)
        ) {$charset_collate};";

        $sql2 = "CREATE TABLE IF NOT EXISTS {$messages} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            session_id BIGINT UNSIGNED NOT NULL,
            role VARCHAR(16) NOT NULL,
            content LONGTEXT NOT NULL,
            tokens_prompt INT NULL,
            tokens_completion INT NULL,
            created_at DATETIME NOT NULL,
            PRIMARY KEY (id),
            KEY idx_session_id (session_id, id)
        ) {$charset_collate};";

        dbDelta($sql1);
        dbDelta($sql2);
    }
}
