<?php

declare(strict_types=1);

namespace App\Domain\PreSave\Jobs;

use App\Domain\PreSave\PreSaveCampaignRepository;
use App\Domain\PreSave\Services\PreSaveProcessor;
use App\Domain\PreSave\ValueObjects\CampaignStatus;
use App\Framework\Worker\Every;
use App\Framework\Worker\Schedule;

/**
 * Retry Failed Registrations Job
 *
 * Runs every 6 hours to retry failed pre-save registrations
 */
#[Schedule(at: new Every(hours: 6))]
final readonly class RetryFailedRegistrationsJob
{
    public function __construct(
        private PreSaveProcessor $processor,
        private PreSaveCampaignRepository $campaignRepository,
    ) {
    }

    /**
     * @return array<string, mixed>
     */
    public function handle(): array
    {
        // Find campaigns that are released but not completed
        $campaigns = $this->campaignRepository->findAll([
            'status' => CampaignStatus::RELEASED->value,
        ]);

        $totalProcessed = 0;
        $totalSuccessful = 0;
        $results = [];

        foreach ($campaigns as $campaign) {
            $result = $this->processor->retryFailedRegistrations($campaign->id, 3);

            $totalProcessed += $result['processed'];
            $totalSuccessful += $result['successful'];

            if ($result['processed'] > 0) {
                $results[] = [
                    'campaign_id' => $campaign->id,
                    'title' => $campaign->title,
                    ...$result,
                ];
            }
        }

        return [
            'job' => 'retry_failed_registrations',
            'timestamp' => time(),
            'campaigns_checked' => count($campaigns),
            'total_processed' => $totalProcessed,
            'total_successful' => $totalSuccessful,
            'total_failed' => $totalProcessed - $totalSuccessful,
            'results' => $results,
        ];
    }
}
