<?php

use App\Services\MeetingTypeSetupService;
use Illuminate\Database\Migrations\Migration;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

return new class extends Migration
{
    public function up(): void
    {
        $permissionNames = [
            'manage-meeting-types',
            'manage-any-meeting-types',
            'view-meeting-types',
            'create-meeting-types',
            'edit-meeting-types',
            'delete-meeting-types',
        ];

        foreach ($permissionNames as $name) {
            Permission::firstOrCreate(['name' => $name, 'guard_name' => 'web']);
        }

        $meetingTypePermissions = Permission::whereIn('name', $permissionNames)->get();

        $rolesToUpdate = Role::whereHas('permissions', function ($query) {
            $query->whereIn('name', ['manage-meetings', 'manage-reports-meetings']);
        })->get();

        foreach ($rolesToUpdate as $role) {
            $role->givePermissionTo($meetingTypePermissions);
        }

        $companyRole = Role::where('name', 'company')->first();
        if ($companyRole) {
            $companyRole->givePermissionTo($meetingTypePermissions);
        }

        app(MeetingTypeSetupService::class)->seedForAllCompanies(null, true);
    }

    public function down(): void
    {
        // Data seed is not reversed; permissions remain.
    }
};
