<?php

declare(strict_types=1);

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

return new class extends Migration
{
    public function up(): void
    {
        // 兼容已由核心迁移建过表的旧库
        if (Schema::hasTable('redirects')) {
            return;
        }

        Schema::create('redirects', function (Blueprint $table) {
            $table->id();
            $table->string('hash', 16)->unique();
            $table->text('target_url');
            $table->unsignedBigInteger('clicks')->default(0);
            $table->string('status', 20)->default('active'); // active / disabled
            $table->timestamp('last_clicked_at')->nullable();
            $table->timestamps();

            // MySQL 5.7 不支持对 TEXT 建全值索引，用前缀索引
            $table->index([DB::raw('target_url(191)')], 'redirects_target_url_index');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('redirects');
    }
};
