<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class SeedMarketingDesignVisibilityModules extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('visibility_modules')) {
            return;
        }

        $modules = [
            'leads.edit.assigned' => [
                'label' => 'Edit Assigned Leads',
                'group' => 'Leads',
                'description' => 'Edit lead details for tasks assigned to you (marketing)',
            ],
            'leads.assign.design' => [
                'label' => 'Assign Design Tasks',
                'group' => 'Leads',
                'description' => 'Assign leads to 3D / CAD team from marketing tasks',
            ],
            'leads.design_tasks' => [
                'label' => 'My Design Tasks',
                'group' => 'Leads',
                'description' => 'View leads assigned for 3D / CAD design work',
            ],
        ];

        $maxOrder = (int) DB::table('visibility_modules')->max('sort_order');
        $now = now();

        foreach ($modules as $key => $meta) {
            if (DB::table('visibility_modules')->where('key', $key)->exists()) {
                continue;
            }
            DB::table('visibility_modules')->insert([
                'key' => $key,
                'label' => $meta['label'],
                'group' => $meta['group'],
                'description' => $meta['description'],
                'is_active' => true,
                'sort_order' => ++$maxOrder,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        }

        if (!class_exists(\App\Services\VisibilityService::class)) {
            return;
        }

        $visibility = app(\App\Services\VisibilityService::class);
        foreach (array_keys($modules) as $key) {
            $visibility->provisionModulePermissions($key);
        }

        $marketing = \App\Models\Department::where('slug', 'marketing')->first();
        if ($marketing) {
            $visibility->syncDepartmentPermissions($marketing->id, [
                'leads.my_tasks',
                'leads.view',
                'leads.remarks',
                'leads.status',
                'leads.edit.assigned',
                'vendor_quotes.manage',
                'leads.assign.design',
            ]);
        }

        $cad = \App\Models\Department::where('slug', 'cad')->first();
        if ($cad) {
            $existing = array_keys(array_filter(
                $visibility->departmentPermissionsMap($cad->id),
                fn ($allowed) => $allowed
            ));
            foreach (['leads.design_tasks', 'leads.view', 'leads.remarks', 'leads.status'] as $mod) {
                if (!in_array($mod, $existing, true)) {
                    $existing[] = $mod;
                }
            }
            $visibility->syncDepartmentPermissions($cad->id, $existing);
        }
    }

    public function down()
    {
        if (!Schema::hasTable('visibility_modules')) {
            return;
        }

        DB::table('visibility_modules')->whereIn('key', [
            'leads.edit.assigned',
            'leads.assign.design',
            'leads.design_tasks',
        ])->delete();
    }
}
