<?php

use Illuminate\Database\Migrations\Migration;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

return new class extends Migration
{
    public function up(): void
    {
        $permissions = collect(['olt.view', 'olt.create', 'olt.update', 'olt.delete'])
            ->mapWithKeys(fn ($name) => [$name => Permission::firstOrCreate(['name' => $name, 'guard_name' => 'web'])]);

        Role::where('name', 'Admin')->first()?->givePermissionTo($permissions->values());
        Role::where('name', 'Manager')->first()?->givePermissionTo($permissions->only(['olt.view', 'olt.update'])->values());
        Role::whereIn('name', ['Billing Operator', 'Support'])->get()->each(fn (Role $role) => $role->givePermissionTo($permissions['olt.view']));
        app(\Spatie\Permission\PermissionRegistrar::class)->forgetCachedPermissions();
    }

    public function down(): void
    {
        Permission::whereIn('name', ['olt.view', 'olt.create', 'olt.update', 'olt.delete'])->delete();
        app(\Spatie\Permission\PermissionRegistrar::class)->forgetCachedPermissions();
    }
};
