<?php

namespace App\Console\Commands;

use App\Models\ReportSchedule;
use App\Services\Reports\ReportScheduleRunner;
use Illuminate\Console\Command;

class RunScheduledReportsCommand extends Command
{
    protected $signature = 'dw:run-scheduled-reports {schedule_id?} {--force}';

    protected $description = 'Süresi gelen otomatik rapor planlarını çalıştırır ve mail gönderir.';

    public function handle(ReportScheduleRunner $runner): int
    {
        $scheduleId = $this->argument('schedule_id');

        if ($scheduleId) {
            $schedule = ReportSchedule::findOrFail((int) $scheduleId);
            $report = $runner->runSchedule($schedule, (bool) $this->option('force'));
            $this->info('Plan çalıştı. Rapor #' . $report->id . ' / ' . $report->status);

            if ($report->error_message) {
                $this->error($report->error_message);
            }

            return $report->status === 'completed' ? self::SUCCESS : self::FAILURE;
        }

        $reports = $runner->runDue((bool) $this->option('force'));
        $this->info(count($reports) . ' plan çalıştırıldı.');

        foreach ($reports as $report) {
            $this->line('#' . $report->id . ' / ' . $report->client?->company_name . ' / ' . $report->status);
        }

        return self::SUCCESS;
    }
}
