<?php
namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\User;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class RoleAndAdminSeeder extends Seeder
{
    public function run(): void
    {
        // Define all models that need permissions
        $models = [
            'user',
            'role',
            'permission',
            'configuration',
            'plainte',
            'financement',
            
        ];

        // Standard CRUD permissions
        $actions = ['list', 'create', 'edit', 'delete', 'show'];
        
        // Special permissions for specific models
        $specialPermissions = [
            'user' => ['impersonate', 'change-password'],
            'role' => ['assign', 'revoke'],
            'article'=> ['approve','reject','export'],
            'categorie'=> ['approve','reject','export'],
            'financement'=> ['approve','reject','export'],
            'plainte'=> ['approve','reject','export','recevoir', 'exameniner','assigner'],
        ];
        
        // Create standard CRUD permissions for all models
        foreach ($models as $model) {
            foreach ($actions as $action) {
                $permission = "{$model}-{$action}";
                Permission::firstOrCreate(['name' => $permission]);
            }
            
            // Add special permissions if they exist for the model
            if (array_key_exists($model, $specialPermissions)) {
                foreach ($specialPermissions[$model] as $action) {
                    $permission = "{$model}-{$action}";
                    Permission::firstOrCreate(['name' => $permission]);
                }
            }

        }

        Permission::firstOrCreate(['name' => 'logs']);

        // Création des rôles
        $adminRole = Role::findOrCreate('admin');        
        // $editorRole = Role::findOrCreate('editor');
        // $journalistRole = Role::findOrCreate('journalist');
        // $validatorRole = Role::findOrCreate('validator');


        // Attribution des permissions aux rôles
        $adminRole->givePermissionTo(Permission::all());
        


        // $editorRole->givePermissionTo($editionPermissions);
        // $validatorRole->givePermissionTo($validationPermissions);
        // $journalistRole->givePermissionTo($editionPermissions);
    

        // Admin User
        $admin = User::firstOrCreate(
            ['email' => 'admin@fie.test'],
            [
                'nom' => 'Super Admin',
                'prenom' =>'Rashid',
                'password' => bcrypt('admin123'),
            ]
        );
        $admin->assignRole('admin');
    }
}
