<?php

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

/**
 * Achievements are a UCP-owned concept (none of QBCore/Qbox/ESX ship one
 * natively), so they live on the UCP's own `mysql` connection, keyed by
 * citizen ID string rather than a foreign key into the `fivem` connection
 * — Eloquent can't enforce a cross-connection FK, so ownership is instead
 * checked in AchievementController the same way every other character page
 * checks it (CharacterController::ownedCharacterOrAbort).
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('achievements', function (Blueprint $table) {
            $table->id();
            $table->string('key')->unique();
            $table->string('name');
            $table->string('description');
            $table->string('icon_path')->nullable();
            $table->timestamps();
        });

        Schema::create('character_achievements', function (Blueprint $table) {
            $table->id();
            $table->string('citizen_id')->index();
            $table->foreignId('achievement_id')->constrained()->cascadeOnDelete();
            $table->timestamp('unlocked_at')->useCurrent();

            $table->unique(['citizen_id', 'achievement_id']);
        });
    }

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