<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

class RolePermissionSeeder extends Seeder
{
    public function run(): void
    {
        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        $permissionNames = [
            'view-dashboard',
            'view-academic-terms',
            'create-academic-terms',
            'update-academic-terms',
            'delete-academic-terms',
        ];

        $permissions = [];
        foreach ($permissionNames as $name) {
            $permissions[] = Permission::firstOrCreate(['name' => $name, 'guard_name' => 'web']);
        }

        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        $roles = [
            'mahasiswa' => ['view-dashboard'],
            'dosen' => ['view-dashboard'],
            'staff-admin' => [
                'view-dashboard',
                'view-academic-terms',
                'create-academic-terms',
                'update-academic-terms',
                'delete-academic-terms',
            ],
            'staff-keuangan' => ['view-dashboard'],
            'kaprodi' => ['view-dashboard', 'view-academic-terms'],
            'developer' => $permissionNames,
        ];

        foreach ($roles as $roleName => $rolePermissions) {
            $role = Role::firstOrCreate(['name' => $roleName, 'guard_name' => 'web']);
            $role->givePermissionTo($rolePermissions);
        }
    }
}
