<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

return new class extends Migration
{
    private array $permissions = [
        'list_dashboard',
        'list_my_dashboard',
        'list_my_activities',
        'share_contacts',
        'share_accounts',
        'reopen_completed_leads',
        'assign_deals',
        'assign_accounts',
    ];

    public function up(): void
    {
        foreach ($this->permissions as $permission) {
            Permission::firstOrCreate(['name' => $permission, 'guard_name' => 'web']);
        }

        Role::where('name', 'admin')->get()->each(function (Role $role) {
            $role->givePermissionTo($this->permissions);
        });
    }

    public function down(): void
    {
        $permissionIds = Permission::whereIn('name', $this->permissions)
            ->where('guard_name', 'web')
            ->pluck('id');

        DB::table('role_has_permissions')->whereIn('permission_id', $permissionIds)->delete();
        Permission::whereIn('id', $permissionIds)->delete();
    }
};
