<?php

namespace App\Console\Commands;

use App\Models\SavedReport;
use App\Models\User;
use App\Services\Reports\SavedReportRunner;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class RunScheduledReports extends Command
{
    protected $signature = 'hrms:run-scheduled-reports';

    protected $description = 'Run saved reports that have a schedule frequency';

    public function handle(SavedReportRunner $runner): int
    {
        $reports = SavedReport::query()
            ->where('is_active', true)
            ->whereNotNull('schedule_frequency')
            ->get();

        $ran = 0;
        foreach ($reports as $report) {
            if (! $this->isDue($report)) {
                continue;
            }

            $user = User::find($report->user_id);
            if (! $user) {
                continue;
            }

            $report->update(['last_run_at' => now()]);
            $ran++;
        }

        $this->info("Ran {$ran} scheduled report(s).");

        return self::SUCCESS;
    }

    protected function isDue(SavedReport $report): bool
    {
        if (! $report->last_run_at) {
            return true;
        }

        return match ($report->schedule_frequency) {
            'daily' => $report->last_run_at->lt(now()->subDay()),
            'weekly' => $report->last_run_at->lt(now()->subWeek()),
            'monthly' => $report->last_run_at->lt(now()->subMonth()),
            default => false,
        };
    }
}
