<?php

namespace App\Console\Commands;

use App\Services\BranchContext;
use App\Services\ManagementAlertService;
use App\Services\ModuleManager;
use App\Services\TaskAutomationService;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;

class ProcessManagementWork extends Command
{
    protected $signature = 'management:process-work {--date= : Process tasks and alerts for a specific YYYY-MM-DD date}';
    protected $description = 'Generate configured collection tasks and management alerts.';

    public function handle(TaskAutomationService $tasks, ManagementAlertService $alerts, ModuleManager $modules, BranchContext $context): int
    {
        return $context->systemWide(function () use ($tasks, $alerts, $modules): int {
            $date = $this->option('date') ? CarbonImmutable::parse((string)$this->option('date')) : CarbonImmutable::now();
            $taskResult = $modules->enabled('tasks') ? $tasks->process($date) : ['created' => 0];
            $alertResult = $alerts->process($date);
            $taskMessage = $modules->enabled('tasks')
                ? 'Collection tasks created: '.$taskResult['created']
                : 'Tasks module disabled; task generation skipped';
            $this->info($taskMessage.'; management alerts created: '.$alertResult['created'].'.');
            return self::SUCCESS;
        });
    }
}
