<?php

declare(strict_types=1);

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

/**
 * 停车管理系统数据库迁移
 *
 * 依据《道路交通安全法》第三十三条：配建停车场管理。
 * 依据《个人信息保护法》第四十二条：车牌号加密存储。
 * 依据 GA/T 1028.3-2022：车牌识别置信度 ≥ 0.85。
 */
return new class extends Migration
{
    public function up(): void
    {
        // 停车场
        Schema::create('kylin_parking_lots', function (Blueprint $table) {
            $table->id();
            $table->string('name', 100)->comment('停车场名称');
            $table->string('address', 200)->nullable()->comment('地址');
            $table->unsignedInteger('total_spaces')->default(0)->comment('总车位数');
            $table->unsignedInteger('available_spaces')->default(0)->comment('可用车位数');
            $table->string('status', 20)->default('active')->comment('状态');
            $table->timestamps();
            $table->softDeletes();
        });

        // 停车记录
        Schema::create('kylin_parking_records', function (Blueprint $table) {
            $table->id();
            $table->foreignId('lot_id')->constrained('kylin_parking_lots')->cascadeOnDelete()->comment('停车场 ID');
            $table->text('plate_no')->comment('车牌号（加密）');
            $table->dateTime('entry_at')->comment('入场时间');
            $table->dateTime('exit_at')->nullable()->comment('出场时间');
            $table->unsignedInteger('duration_minutes')->nullable()->comment('停车时长（分钟）');
            $table->unsignedInteger('fee')->default(0)->comment('费用（分）');
            $table->string('pay_method', 20)->nullable()->comment('支付方式');
            $table->string('status', 20)->default('parking')->comment('状态');
            $table->timestamps();

            $table->index('entry_at');
            $table->index(['lot_id', 'status']);
        });

        // 月卡
        Schema::create('kylin_parking_monthly_cards', function (Blueprint $table) {
            $table->id();
            $table->foreignId('lot_id')->constrained('kylin_parking_lots')->cascadeOnDelete()->comment('停车场 ID');
            $table->text('plate_no')->comment('车牌号（加密）');
            $table->string('owner_name', 50)->comment('车主姓名');
            $table->text('owner_phone')->nullable()->comment('车主手机号（加密）');
            $table->dateTime('start_at')->comment('生效日期');
            $table->dateTime('expired_at')->comment('到期日期');
            $table->string('status', 20)->default('active')->comment('状态');
            $table->timestamps();

            $table->index('expired_at');
            $table->index(['lot_id', 'status']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('kylin_parking_monthly_cards');
        Schema::dropIfExists('kylin_parking_records');
        Schema::dropIfExists('kylin_parking_lots');
    }
};