<?php

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

return new class extends Migration
{
    public function up(): void
    {
        app(PermissionRegistrar::class)->forgetCachedPermissions();
        foreach (['email_templates','messages','follow_ups','todos','projects','cases','surveys','trade_documents'] as $module) {
            foreach (['view','create','update','delete'] as $action) {
                Permission::firstOrCreate(['name'=>"{$action}_{$module}",'guard_name'=>'web']);
            }
        }
        app(PermissionRegistrar::class)->forgetCachedPermissions();
    }

    public function down(): void
    {
        Permission::whereIn('name', collect(['email_templates','messages','follow_ups','todos','projects','cases','surveys','trade_documents'])
            ->flatMap(fn($module)=>collect(['view','create','update','delete'])->map(fn($action)=>"{$action}_{$module}")))->delete();
        app(PermissionRegistrar::class)->forgetCachedPermissions();
    }
};
