<?php

namespace Modules\Identity\Database\Seeders;

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

class RolePermissionSeeder extends Seeder
{
    /**
     * @var list<string>
     */
    protected array $permissions = [
        'manage_catalog',
        'manage_routes',
        'manage_pricing',
        'view_bookings',
        'manage_bookings',
        'view_payments',
        'process_refunds',
        'view_audit_log',
        'manage_staff',
        'manage_roles',
        'view_customers',
        'manage_settings',
        'view_reports',
        'manage_ai_agent',
    ];

    /**
     * @var array<string, list<string>>
     */
    protected array $roles = [
        'super_admin' => [
            'manage_catalog',
            'manage_routes',
            'manage_pricing',
            'view_bookings',
            'manage_bookings',
            'view_payments',
            'process_refunds',
            'view_audit_log',
            'manage_staff',
            'manage_roles',
            'view_customers',
            'manage_settings',
            'view_reports',
            'manage_ai_agent',
        ],
        'admin' => [
            'manage_catalog',
            'manage_routes',
            'manage_pricing',
            'view_bookings',
            'manage_bookings',
            'view_payments',
            'process_refunds',
            'view_audit_log',
            'view_customers',
            'manage_settings',
            'view_reports',
            'manage_ai_agent',
        ],
        'support' => [
            'view_bookings',
            'view_payments',
            'view_audit_log',
            'view_customers',
        ],
    ];

    public function run(): void
    {
        foreach ($this->permissions as $permission) {
            Permission::findOrCreate($permission, 'web');
        }

        // WithoutModelEvents (used by DatabaseSeeder) suppresses the model
        // events Spatie's permission cache relies on to invalidate itself,
        // so the freshly created permissions above must be flushed manually.
        app(PermissionRegistrar::class)->forgetCachedPermissions();

        foreach ($this->roles as $role => $permissions) {
            Role::findOrCreate($role, 'web')->syncPermissions($permissions);
        }
    }
}
