<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    public function up()
    {
        if (!Schema::hasTable('user_login')) {
            return;
        }

        Schema::table('user_login', function (Blueprint $table) {
            if (!Schema::hasColumn('user_login', 'login_account')) {
                $table->string('login_account', 64)->default('')->comment('尝试登录的账号（失败时可能无 user_id）')->after('user_id');
            }
            if (!Schema::hasColumn('user_login', 'country')) {
                $table->string('country', 128)->default('')->comment('国家/地区')->after('login_ip');
            }
            if (!Schema::hasColumn('user_login', 'browser')) {
                $table->string('browser', 128)->default('')->comment('浏览器')->after('country');
            }
            if (!Schema::hasColumn('user_login', 'os')) {
                $table->string('os', 128)->default('')->comment('操作系统')->after('browser');
            }
            if (!Schema::hasColumn('user_login', 'status')) {
                $table->tinyInteger('status')->default(1)->comment('状态：1登录成功 0登录失败')->after('os');
            }
            if (!Schema::hasColumn('user_login', 'logout_time')) {
                $table->dateTime('logout_time')->nullable()->comment('登出时间')->after('status');
            }
            if (!Schema::hasColumn('user_login', 'online_duration')) {
                $table->unsignedInteger('online_duration')->nullable()->comment('在线时长（分钟，仅登出后写入）')->after('logout_time');
            }
            if (!Schema::hasColumn('user_login', 'user_agent')) {
                $table->string('user_agent', 512)->default('')->comment('User-Agent 原始字符串')->after('online_duration');
            }
        });
    }

    public function down()
    {
        if (!Schema::hasTable('user_login')) {
            return;
        }

        $columns = ['login_account', 'country', 'browser', 'os', 'status', 'logout_time', 'online_duration', 'user_agent'];
        $existing = array_values(array_filter($columns, fn ($col) => Schema::hasColumn('user_login', $col)));
        if ($existing === []) {
            return;
        }

        Schema::table('user_login', function (Blueprint $table) use ($existing) {
            $table->dropColumn($existing);
        });
    }
};
