<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // 修改默认 users 表，添加 kylin 扩展字段
        if (Schema::hasTable('users')) {
            Schema::table('users', function (Blueprint $table) {
                $columns = Schema::getColumnListing('users');
                if (!in_array('phone', $columns)) {
                    $table->string('phone', 20)->nullable()->unique()->after('email');
                }
                if (!in_array('avatar', $columns)) {
                    $table->string('avatar', 500)->nullable()->after('phone');
                }
                if (!in_array('status', $columns)) {
                    $table->unsignedTinyInteger('status')->default(1)->after('avatar')->comment('0禁用1正常2锁定');
                }
                if (!in_array('login_ip', $columns)) {
                    $table->string('login_ip', 45)->nullable()->after('status');
                }
                if (!in_array('login_at', $columns)) {
                    $table->timestamp('login_at')->nullable()->after('login_ip');
                }
                if (!in_array('password_changed_at', $columns)) {
                    $table->timestamp('password_changed_at')->nullable()->after('login_at');
                }
                if (!in_array('deleted_at', $columns)) {
                    $table->softDeletes();
                }
            });
        }

        Schema::create('kylin_user_profiles', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->string('real_name', 50)->nullable()->comment('真实姓名');
            $table->string('id_card', 20)->nullable()->comment('身份证号');
            $table->unsignedTinyInteger('gender')->default(0)->comment('0未知1男2女');
            $table->date('birthday')->nullable();
            $table->string('province', 50)->nullable();
            $table->string('city', 50)->nullable();
            $table->string('district', 50)->nullable();
            $table->string('address', 255)->nullable();
            $table->string('company', 100)->nullable();
            $table->string('position', 50)->nullable();
            $table->json('extra')->nullable()->comment('扩展字段');
            $table->timestamps();

            $table->unique('user_id');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('kylin_user_profiles');
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn([
                'phone', 'avatar', 'status', 'login_ip',
                'login_at', 'password_changed_at', 'deleted_at',
            ]);
        });
    }
};
