<?php

namespace Database\Seeders;

use App\Support\PermissionCatalog;
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();

        $master = PermissionCatalog::MASTER;
        $academicClasses = PermissionCatalog::ACADEMIC_CLASSES;
        $manage = PermissionCatalog::MANAGE;
        $finances = PermissionCatalog::FINANCES;
        $services = PermissionCatalog::SERVICES;
        $users = PermissionCatalog::USERS;

        $feedbackSelfService = [
            'view-feedback',
            'create-feedback',
            'update-feedback',
            'delete-feedback',
        ];

        $permissionNames = PermissionCatalog::all();

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

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

        $roles = [
            'mahasiswa' => [
                'view-dashboard',
                'view-academic-terms',
                'view-courses',
                'view-letter-requests',
                'create-letter-requests',
                'update-letter-requests',
                'delete-letter-requests',
                ...$feedbackSelfService,
            ],
            'dosen' => [
                'view-dashboard',
                'view-courses',
                ...$feedbackSelfService,
            ],
            'staff-admin' => [
                'view-dashboard',
                ...$master,
                ...$academicClasses,
                ...$manage,
                ...array_diff($services, ['create-letter-requests', 'update-letter-requests']),
                ...$users,
                ...$feedbackSelfService,
                'update-feedback-status',
            ],
            'staff-keuangan' => [
                'view-dashboard',
                ...$finances,
                ...$feedbackSelfService,
            ],
            'kaprodi' => [
                'view-dashboard',
                'view-academic-terms',
                'view-courses',
                'view-course-classes',
                'view-course-registrations',
                'view-students',
                ...$feedbackSelfService,
            ],
            'developer' => $permissionNames,
        ];

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