<?php

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::table('roles', function (Blueprint $table) {
            $table->json('permissions')->nullable()->after('access_level');
        });

        $allPermissions = [
            'dashboard.view',
            'contacts.view',
            'contacts.update',
            'contacts.delete',
            'pages.view',
            'pages.create',
            'pages.update',
            'pages.delete',
            'blog_posts.view',
            'blog_posts.create',
            'blog_posts.update',
            'blog_posts.delete',
            'services.view',
            'services.create',
            'services.update',
            'services.delete',
            'settings.view',
            'settings.update',
            'settings.refresh',
            'media.view',
            'media.upload',
            'media.replace',
            'media.delete',
            'media.reorder',
            'users.view',
            'users.create',
            'users.update',
            'users.delete',
            'roles.view',
            'roles.create',
            'roles.update',
            'roles.delete',
            'audits.view',
            'backups.download',
        ];

        $editorPermissions = [
            'dashboard.view',
            'contacts.view',
            'contacts.update',
            'contacts.delete',
            'pages.view',
            'pages.create',
            'pages.update',
            'pages.delete',
            'blog_posts.view',
            'blog_posts.create',
            'blog_posts.update',
            'blog_posts.delete',
            'services.view',
            'services.create',
            'services.update',
            'services.delete',
        ];

        DB::table('roles')
            ->orderBy('id')
            ->get()
            ->each(function ($role) use ($allPermissions, $editorPermissions): void {
                $permissions = match ($role->slug) {
                    'admin' => $allPermissions,
                    'editor' => $editorPermissions,
                    default => [],
                };

                DB::table('roles')
                    ->where('id', $role->id)
                    ->update(['permissions' => json_encode($permissions)]);
            });
    }

    public function down(): void
    {
        Schema::table('roles', function (Blueprint $table) {
            $table->dropColumn('permissions');
        });
    }
};
