<?php

declare(strict_types=1);

namespace App\Application\Jobs;

use App\Domain\Jobs\Job;
use App\Domain\Jobs\JobContext;
use App\Domain\Jobs\JobResult;
use Doctrine\DBAL\Connection;

/**
 * Prunes `audit_log` rows older than `JOB_AUDIT_RETENTION_DAYS`.
 *
 * The audit emitter lands in M12; until then the table will be empty and
 * this job will routinely return 0 items processed. Running it now keeps
 * the schedule honest and surfaces any DB connectivity issues early.
 */
final class CleanupAuditJob implements Job
{
    public const NAME = 'cleanup-audit';

    public function __construct(
        private readonly Connection $connection,
        private readonly int $retentionDays = 180,
    ) {
    }

    public function name(): string
    {
        return self::NAME;
    }

    public function defaultIntervalSeconds(): int
    {
        return 86400;
    }

    public function maxRuntimeSeconds(): int
    {
        return 60;
    }

    public function run(JobContext $context): JobResult
    {
        $cutoff = $context->clock->now()->modify(sprintf('-%d days', $this->retentionDays));
        $deleted = (int) $this->connection->executeStatement(
            'DELETE FROM audit_log WHERE created_at < :cutoff',
            ['cutoff' => $cutoff->format('Y-m-d H:i:s')],
        );

        return new JobResult(
            itemsProcessed: $deleted,
            details: ['retention_days' => $this->retentionDays],
        );
    }
}
