<?php

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

return new class extends Migration
{
    public function up(): void
    {
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        $permissions = [
            'view-purchase-returns',
            'create-purchase-returns',
            'manage-purchase-returns',
        ];

        foreach ($permissions as $permission) {
            Permission::firstOrCreate(['name' => $permission]);
        }

        // Assign to relevant roles
        $rolePermissions = [
            'super-admin'       => $permissions,
            'org-owner'         => $permissions,
            'admin'             => $permissions,
            'inventory-manager' => ['view-purchase-returns', 'create-purchase-returns', 'manage-purchase-returns'],
            'store-keeper'      => ['view-purchase-returns', 'create-purchase-returns'],
        ];

        foreach ($rolePermissions as $roleName => $perms) {
            $role = \Spatie\Permission\Models\Role::where('name', $roleName)->first();
            if ($role) {
                $role->givePermissionTo($perms);
            }
        }
    }

    public function down(): void
    {
        $permissions = ['view-purchase-returns', 'create-purchase-returns', 'manage-purchase-returns'];
        foreach ($permissions as $name) {
            Permission::where('name', $name)->delete();
        }
    }
};
