<?php

namespace App\Console\Commands;

use App\Services\System\ConfigUpdateService;
use DateTimeZone;
use Illuminate\Console\Command;

class ConfigUpdateCommand extends Command
{
    protected $signature = 'config:update {task?} {--task=} {--dry} {--force} {--tz=}';
    protected $description = 'Run a configuration update task (weekly cron).';

    public function handle(ConfigUpdateService $service): int
    {
        $task = (string) ($this->option('task') ?: $this->argument('task') ?: '');
        $dry = (bool) $this->option('dry');
        $force = (bool) $this->option('force');
        $tzName = (string) ($this->option('tz') ?: (config('School')->attendance['timezone'] ?? 'UTC'));
        $tz = new DateTimeZone($tzName);

        if ($task === '' || !in_array($task, $service->availableTasks(), true)) {
            $this->error('Invalid or missing --task. Available: ' . implode(', ', $service->availableTasks()));
            return self::FAILURE;
        }

        $result = $service->runTask($task, $dry, $force, $tz);
        if (!$result['ok']) {
            $this->error($result['message'] ?? "Task '{$task}' failed.");
            return self::FAILURE;
        }

        $this->info("Task '{$task}' finished successfully." . ($dry ? ' [DRY RUN]' : ''));

        return self::SUCCESS;
    }
}
