<?php

use Hyperf\Database\Schema\Schema;
use Hyperf\Database\Schema\Blueprint;
use Hyperf\Database\Migrations\Migration;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('api_keys', function (Blueprint $table) {
            $table->bigIncrements('id')->comment('主键');
            $table->unsignedBigInteger('user_id')->comment('所属用户');
            $table->string('name', 100)->comment('用户自定义名称');
            $table->string('key_hash', 255)->unique()->comment('SHA256 哈希');
            $table->string('key_prefix', 8)->comment('明文前 8 位，用于识别');
            $table->timestampTz('last_used_at')->nullable()->comment('最后使用时间');
            $table->timestampTz('expires_at')->nullable()->comment('过期时间，NULL 永不过期');
            $table->boolean('enabled')->default(true)->comment('是否启用');
            $table->timestampTz('created_at')->useCurrent();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->index('user_id', 'idx_api_keys_user_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('api_keys');
    }
};
