<?php

use App\Support\PermissionCatalog;
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
    {
        Schema::create('model_permissions', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('module')->index();
            $table->string('sub_module')->index();
            $table->string('action')->index();
            $table->string('guard_name')->default('web');
            $table->string('description')->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        $now = now();
        $permissions = collect(PermissionCatalog::permissionNames())
            ->map(function (string $permission) use ($now) {
                return array_merge(PermissionCatalog::metadata($permission), [
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);
            })
            ->all();

        DB::table('model_permissions')->upsert(
            $permissions,
            ['name'],
            ['module', 'sub_module', 'action', 'guard_name', 'is_active', 'updated_at']
        );
    }

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