<?php

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

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

        $modules = [
            'leads.assign' => [
                'label' => 'Assign Leads to Marketing',
                'group' => 'Leads',
                'description' => 'Assign leads to marketing team members from listing',
            ],
            'leads.my_tasks' => [
                'label' => 'My Marketing Tasks',
                'group' => 'Leads',
                'description' => 'View leads assigned to the logged-in marketing user',
            ],
        ];

        $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)) {
            $visibility = app(\App\Services\VisibilityService::class);
            foreach (array_keys($modules) as $key) {
                $visibility->provisionModulePermissions($key);
            }

            $sales = \App\Models\Department::where('slug', 'sales')->first();
            if ($sales) {
                $existing = array_keys(array_filter(
                    $visibility->departmentPermissionsMap($sales->id),
                    fn ($allowed) => $allowed
                ));
                if (!in_array('leads.assign', $existing, true)) {
                    $existing[] = 'leads.assign';
                }
                $visibility->syncDepartmentPermissions($sales->id, $existing);
            }

            $marketing = \App\Models\Department::firstOrCreate(
                ['slug' => 'marketing'],
                ['name' => 'Marketing', 'description' => 'Marketing team', 'is_active' => true]
            );
            $visibility->syncDepartmentPermissions($marketing->id, [
                'leads.my_tasks',
                'leads.view',
                'leads.remarks',
                'leads.status',
            ]);
        }
    }

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

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