<?php

namespace Database\Seeders;

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

class RbacSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $dealers = Dealer::query()->get();

        $guardName = 'web';
        $roles = config('mtt_roles', []);
        $permissions = config('mtt_permissions', []);
        $matrix = config('mtt_rbac_matrix', []);
        $registrar = app(PermissionRegistrar::class);
        $excludedDealerRoles = config('mtt_tenant_baseline.excluded_roles_for_dealers', []);

        $registrar->forgetCachedPermissions();
        $registrar->setPermissionsTeamId(null);

        foreach ($permissions as $permissionName) {
            Permission::findOrCreate($permissionName, $guardName);
        }

        foreach ($dealers as $dealer) {
            $registrar->setPermissionsTeamId($dealer->id);

            foreach ($roles as $roleName) {
                if (in_array($roleName, $excludedDealerRoles, true)) {
                    continue;
                }

                $role = Role::findOrCreate($roleName, $guardName, $dealer->id);
                $permissionNames = $matrix[$roleName] ?? [];

                foreach ($permissionNames as $permissionName) {
                    Permission::findOrCreate($permissionName, $guardName);
                }

                $role->syncPermissions($permissionNames);
            }
        }

        $registrar->setPermissionsTeamId(null);
        $registrar->forgetCachedPermissions();
    }
}
