<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;
use App\Core\Logger;

/**
 * Checks locker rental expiry and manages grace period transitions.
 * - Active rentals past end_date → grace_period
 * - Grace period rentals past 3 months → pending_eviction
 */
class LockerGraceCheckJob
{
    private Database $db;

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

    public function shouldRun(): bool
    {
        // Run daily
        return true;
    }

    public function run(): array
    {
        $ts = date('Y-m-d H:i:s');
        $today = date('Y-m-d');
        $processed = 0;

        // 1. Active rentals past end_date → grace_period
        $expired = $this->db->select(
            "SELECT id FROM sa_locker_rentals
             WHERE status = 'active'
               AND end_date < ?
               AND is_archived = 0",
            [$today]
        );

        foreach ($expired as $row) {
            $this->db->update('sa_locker_rentals', [
                'status'           => 'grace_period',
                'grace_started_at' => $today,
                'updated_at'       => $ts,
            ], 'id = ?', [(int) $row['id']]);
            $processed++;
        }

        // 2. Grace period rentals past 3 months → pending_eviction
        $overGrace = $this->db->select(
            "SELECT id FROM sa_locker_rentals
             WHERE status = 'grace_period'
               AND grace_started_at <= DATE_SUB(?, INTERVAL 3 MONTH)
               AND is_archived = 0",
            [$today]
        );

        foreach ($overGrace as $row) {
            $this->db->update('sa_locker_rentals', [
                'status'     => 'pending_eviction',
                'updated_at' => $ts,
            ], 'id = ?', [(int) $row['id']]);
            $processed++;
        }

        Logger::info("LockerGraceCheck: {$processed} rentals updated (expired=" . count($expired) . ", over_grace=" . count($overGrace) . ")");

        return ['processed' => $processed];
    }
}
