<?php

namespace Database\Seeders;

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

class UserSeeder extends Seeder
{
    public function run(): void
    {
        // Créer les permissions
        $permissions = [
            'view_dashboard',
            'manage_products',
            'manage_clients',
            'manage_suppliers',
            'manage_quotes',
            'manage_invoices',
            'manage_stock',
            'manage_payments',
            'manage_settings',
            'manage_users',
        ];

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

        // Créer les rôles
        $adminRole = Role::firstOrCreate(['name' => 'admin']);
        $managerRole = Role::firstOrCreate(['name' => 'manager']);
        $employeeRole = Role::firstOrCreate(['name' => 'employee']);

        // Assigner toutes les permissions à l'admin
        $adminRole->givePermissionTo(Permission::all());

        // Assigner certaines permissions au manager
        $managerRole->givePermissionTo([
            'view_dashboard',
            'manage_products',
            'manage_clients',
            'manage_suppliers',
            'manage_quotes',
            'manage_invoices',
            'manage_stock',
            'manage_payments',
        ]);

        // Assigner des permissions limitées à l'employé
        $employeeRole->givePermissionTo([
            'view_dashboard',
            'manage_products',
            'manage_clients',
            'manage_quotes',
            'manage_invoices',
        ]);

        // Créer l'utilisateur admin
        $admin = User::firstOrCreate(
            ['email' => 'admin@gstock.com'],
            [
                'name' => 'Administrateur',
                'password' => Hash::make('password'),
            ]
        );

        $admin->assignRole('admin');

        // Créer un utilisateur manager
        $manager = User::firstOrCreate(
            ['email' => 'manager@gstock.com'],
            [
                'name' => 'Manager',
                'password' => Hash::make('password'),
            ]
        );

        $manager->assignRole('manager');
    }
}