<?php

use App\Models\Department;
use App\Services\VisibilityService;
use Illuminate\Database\Migrations\Migration;

class SyncDesignDepartmentPermissions extends Migration
{
    public function up()
    {
        if (!class_exists(VisibilityService::class)) {
            return;
        }

        $visibility = app(VisibilityService::class);
        $designPermissions = [
            'leads.design_tasks',
            'leads.view',
            'leads.remarks',
            'leads.status',
            'tasks.cad',
            'tasks.general',
        ];

        foreach (config('departments.design_team_slugs', []) as $slug) {
            $dept = Department::where('slug', $slug)->first();
            if (!$dept) {
                continue;
            }

            $existing = array_keys(array_filter(
                $visibility->departmentPermissionsMap($dept->id),
                fn ($allowed) => $allowed
            ));

            foreach ($designPermissions as $mod) {
                if (!in_array($mod, $existing, true)) {
                    $existing[] = $mod;
                }
            }

            $visibility->syncDepartmentPermissions($dept->id, $existing);
        }
    }

    public function down()
    {
        //
    }
}
