<?php

namespace Database\Seeders;

use App\Enums\PermissionSlug;
use App\Enums\RoleSlug;
use App\Models\Permission;
use App\Models\Role;
use Illuminate\Database\Seeder;

class RoleSeeder extends Seeder
{
    public function run(): void
    {
        $this->call(PermissionSeeder::class);

        $permissions = Permission::query()
            ->get()
            ->keyBy(fn (Permission $permission): string => $permission->slug->value);

        foreach (RoleSlug::cases() as $roleSlug) {
            $role = Role::query()->updateOrCreate(
                ['slug' => $roleSlug],
                [
                    'name' => $roleSlug->label(),
                    'description' => $roleSlug->description(),
                ],
            );

            $role->permissions()->sync(
                array_map(
                    fn (PermissionSlug $permission): int => $permissions[$permission->value]->id,
                    $roleSlug->permissions(),
                ),
            );
        }
    }
}
