<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\App;
use App\Core\Database;
use App\Core\Logger;
use App\Modules\Subscriptions\Services\SubscriptionGenerator;

class SubscriptionGeneratorJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }

    public function shouldRun(): bool
    {
        // Run in July days 1-7 (financial year starts July 1st)
        return (int) date('n') === 7 && (int) date('j') <= 7;
    }

    public function run(): array
    {
        $year = (int) date('Y');
        $financialYear = $year . '/' . ($year + 1);

        // Check if already generated (any rows for this FY means done)
        $existing = $this->db->selectOne(
            "SELECT COUNT(*) as c FROM subscriptions WHERE financial_year = ?",
            [$financialYear]
        );
        if ((int) ($existing['c'] ?? 0) > 0) {
            return ['processed' => 0];
        }

        // Boot App singleton so services can access db()
        $app = App::getInstance();
        if (!$app->db()) {
            $app->setDb($this->db);
        }

        // Delegate to the full-featured SubscriptionGenerator service
        // which handles: exemptions, year-specific rates, discounts, per-person dedup
        $result = SubscriptionGenerator::generateForYear($financialYear);

        $processed = ($result['created'] ?? 0) + ($result['skipped'] ?? 0);
        Logger::info("Subscription generation (cron) complete for {$financialYear}: created={$result['created']}, skipped={$result['skipped']}");

        return ['processed' => $result['created'] ?? 0];
    }
}
