<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * 将已发布的 v0.7.2 对话表对齐到 laravel/ai v0.11.0。
 *
 * 不改写已执行的 2026_08_19_070130 创建迁移，也不再复制一套对话表。
 */
return new class extends Migration
{
    public function up(): void
    {
        $conversationsTable = $this->conversationsTable();
        $messagesTable = $this->messagesTable();

        if (! Schema::hasTable($conversationsTable) || ! Schema::hasTable($messagesTable)) {
            return;
        }

        $this->alignConversationsTable($conversationsTable);
        $this->alignMessagesTable($messagesTable);
        $this->addApprovalState($messagesTable);
    }

    public function down(): void
    {
        $conversationsTable = $this->conversationsTable();
        $messagesTable = $this->messagesTable();

        if (! Schema::hasTable($conversationsTable) || ! Schema::hasTable($messagesTable)) {
            return;
        }

        $this->dropApprovalState($messagesTable);
        $this->revertMessagesTable($messagesTable);
        $this->revertConversationsTable($conversationsTable);
    }

    private function conversationsTable(): string
    {
        return (string) config('ai.conversations.tables.conversations', 'agent_conversations');
    }

    private function messagesTable(): string
    {
        return (string) config('ai.conversations.tables.messages', 'agent_conversation_messages');
    }

    private function alignConversationsTable(string $tableName): void
    {
        if (Schema::hasColumn($tableName, 'participant_id')) {
            return;
        }

        Schema::table($tableName, function (Blueprint $table) use ($tableName): void {
            if (Schema::hasIndex($tableName, ['user_id', 'updated_at'])) {
                $table->dropIndex(['user_id', 'updated_at']);
            }

            $table->renameColumn('user_id', 'participant_id');
            $table->string('participant_type')->nullable()->after('id');
        });

        $this->backfillParticipantType($tableName);

        Schema::table($tableName, function (Blueprint $table): void {
            $table->index(
                ['participant_type', 'participant_id', 'updated_at'],
                'participant_updated_at_index',
            );
        });
    }

    private function alignMessagesTable(string $tableName): void
    {
        if (Schema::hasColumn($tableName, 'participant_id')) {
            return;
        }

        Schema::table($tableName, function (Blueprint $table) use ($tableName): void {
            if (Schema::hasIndex($tableName, 'conversation_index')) {
                $table->dropIndex('conversation_index');
            }

            if (Schema::hasIndex($tableName, ['user_id'])) {
                $table->dropIndex(['user_id']);
            }

            $table->renameColumn('user_id', 'participant_id');
            $table->string('participant_type')->nullable()->after('conversation_id');
        });

        $this->backfillParticipantType($tableName);

        Schema::table($tableName, function (Blueprint $table): void {
            $table->index(
                ['conversation_id', 'participant_type', 'participant_id', 'updated_at'],
                'conversation_index',
            );
            $table->index(['participant_type', 'participant_id'], 'participant_index');
        });
    }

    private function addApprovalState(string $tableName): void
    {
        if (Schema::hasColumn($tableName, 'approval_state')) {
            return;
        }

        Schema::table($tableName, function (Blueprint $table): void {
            $table->text('approval_state')->nullable()->after('meta');
        });
    }

    private function dropApprovalState(string $tableName): void
    {
        if (! Schema::hasColumn($tableName, 'approval_state')) {
            return;
        }

        Schema::table($tableName, function (Blueprint $table): void {
            $table->dropColumn('approval_state');
        });
    }

    private function revertConversationsTable(string $tableName): void
    {
        if (! Schema::hasColumn($tableName, 'participant_id')) {
            return;
        }

        Schema::table($tableName, function (Blueprint $table) use ($tableName): void {
            if (Schema::hasIndex($tableName, 'participant_updated_at_index')) {
                $table->dropIndex('participant_updated_at_index');
            }

            $table->dropColumn('participant_type');
            $table->renameColumn('participant_id', 'user_id');
        });

        Schema::table($tableName, function (Blueprint $table): void {
            $table->index(['user_id', 'updated_at']);
        });
    }

    private function revertMessagesTable(string $tableName): void
    {
        if (! Schema::hasColumn($tableName, 'participant_id')) {
            return;
        }

        Schema::table($tableName, function (Blueprint $table) use ($tableName): void {
            if (Schema::hasIndex($tableName, 'conversation_index')) {
                $table->dropIndex('conversation_index');
            }

            if (Schema::hasIndex($tableName, 'participant_index')) {
                $table->dropIndex('participant_index');
            }

            $table->dropColumn('participant_type');
            $table->renameColumn('participant_id', 'user_id');
        });

        Schema::table($tableName, function (Blueprint $table): void {
            $table->index(['conversation_id', 'user_id', 'updated_at'], 'conversation_index');
            $table->index(['user_id']);
        });
    }

    private function backfillParticipantType(string $tableName): void
    {
        $participantType = (new User)->getMorphClass();

        DB::table($tableName)
            ->whereNotNull('participant_id')
            ->whereNull('participant_type')
            ->update(['participant_type' => $participantType]);
    }
};
