<?php

namespace Database\Seeders;

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

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

        $modules = [
            'dashboard', 'sales', 'purchases', 'expenses',
            'bank-withdrawals',
            'employees', 'rosters', 'employee-payments',
            'customers', 'customer-ledgers',
            'vendors', 'vendor-ledgers',
            'shareholders', 'shareholder-transactions',
            'sale-sources', 'expense-categories', 'employee-salary-histories',
            'items', 'reports', 'shareholder-reports', 'currencies', 'users', 'roles',
        ];

        $actions = ['view', 'create', 'edit', 'delete'];

        foreach ($modules as $module) {
            foreach ($actions as $action) {
                Permission::firstOrCreate(['name' => "{$module}.{$action}"]);
            }
        }

        // Admin — all permissions
        $admin = Role::firstOrCreate(['name' => 'admin']);
        $admin->syncPermissions(Permission::all());

        // Manager — all except user/role management
        $manager = Role::firstOrCreate(['name' => 'manager']);
        $manager->syncPermissions(
            Permission::whereNotIn('name', [
                'users.create', 'users.edit', 'users.delete',
                'roles.create', 'roles.edit', 'roles.delete',
            ])->get()
        );

        // Staff — view + create on operational modules only
        $staff = Role::firstOrCreate(['name' => 'staff']);
        $staffPermissions = [];
        $staffModules = ['dashboard', 'sales', 'purchases', 'expenses', 'employees', 'customers', 'rosters', 'items', 'vendors'];
        foreach ($staffModules as $module) {
            $staffPermissions[] = "{$module}.view";
            $staffPermissions[] = "{$module}.create";
        }
        $staff->syncPermissions($staffPermissions);
    }
}
