<?php

namespace Database\Seeders;

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

class RolesAndPermissionsSeeder extends Seeder
{
    public function run(): void
    {
        // Reset cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // Create permissions
        $permissions = [
            'settings.manage',
            'proclamatori.manage',
            'territori.manage',
            'campagne.manage',
            'registro.view',
            'registro.export',
            'territori.assign',
            'territori.return',
            'audit.view',
            'audit.export',
        ];

        foreach ($permissions as $permission) {
            Permission::firstOrCreate(['name' => $permission]);
        }

        // Amministratore: all permissions
        $admin = Role::firstOrCreate(['name' => 'amministratore']);
        $admin->syncPermissions($permissions);

        // Assistente: proclamatori, campagne, assign, return
        $assistente = Role::firstOrCreate(['name' => 'assistente']);
        $assistente->syncPermissions([
            'proclamatori.manage',
            'campagne.manage',
            'territori.assign',
            'territori.return',
            'registro.view',
        ]);

        // Operatore: assign and return only
        $operatore = Role::firstOrCreate(['name' => 'operatore']);
        $operatore->syncPermissions([
            'territori.assign',
            'territori.return',
        ]);
    }
}
