<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class PermissionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Reset cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // Define Permissions
        $permissions = [
            'manage courses',
            'manage modules',
            'manage lessons',
            'manage vocabularies',
            'manage students',
            'view dashboard',
            'practice srs',
        ];

        foreach ($permissions as $permissionName) {
            $permission = \App\Models\Permission::where('name', $permissionName)->where('guard_name', 'web')->first();
            if (!$permission) {
                \App\Models\Permission::create([
                    'name' => $permissionName,
                    'guard_name' => 'web',
                ]);
            }
        }

        $assign = function($roleName, $perms) {
            $role = \App\Models\Role::where('name', $roleName)->where('guard_name', 'web')->first();
            if ($role) {
                $role->syncPermissions($perms);
            }
        };

        $assign('super_admin', \App\Models\Permission::all());
        $assign('admin', [
            'manage courses',
            'manage modules',
            'manage lessons',
            'manage vocabularies',
            'manage students',
            'view dashboard',
        ]);
        $assign('teacher', [
            'manage courses',
            'manage modules',
            'manage lessons',
            'view dashboard',
        ]);
        $assign('student', [
            'view dashboard',
            'practice srs',
        ]);
    }
}
