<?php

declare(strict_types=1);

namespace App\Services\Sitemaps;

final class SitemapReleaseCleanupService
{
    public function __construct(private readonly SitemapReleaseManager $releases)
    {
    }

    public function cleanup(): int
    {
        $activeReleaseId = $this->releases->activeReleaseId();
        $successfulKeep = max(1, (int) config('sitemaps.releases.retain_successful', 3));
        $failedKeep = max(0, (int) config('sitemaps.releases.retain_failed', 2));

        $successfulSeen = 0;
        $failedSeen = 0;
        $deleted = 0;

        foreach ($this->releases->listReleases() as $release) {
            $releaseId = (string) ($release['release_id'] ?? '');

            if ($releaseId === '' || $releaseId === $activeReleaseId) {
                continue;
            }

            $status = (string) ($release['status'] ?? 'built');

            if ($status === 'published') {
                $successfulSeen++;
                if ($successfulSeen > $successfulKeep) {
                    $this->releases->deleteRelease($releaseId);
                    $deleted++;
                }

                continue;
            }

            $failedSeen++;
            if ($failedSeen > $failedKeep) {
                $this->releases->deleteRelease($releaseId);
                $deleted++;
            }
        }

        return $deleted;
    }
}