<?php

namespace MintyPHP\Repository\User;

use MintyPHP\DB;

/**
 * Counts users in the deletion window for the policy-dashboard tile. Time base is UTC, mirroring
 * {@see UserReadRepository::listIdsForAutoDelete} for behavioural equivalence.
 */
class UserLifecyclePolicyDashboardRepository implements UserLifecyclePolicyDashboardRepositoryInterface
{
    public function countPendingDeletion(int $deleteDays, int $windowDays): int
    {
        if ($deleteDays <= 0 || $windowDays <= 0) {
            return 0;
        }
        // Lower bound (deleteDays - windowDays) is clamped to 0 so a misconfigured tiny deleteDays
        // value cannot produce a negative INTERVAL; the upper bound stays at deleteDays.
        $lowerBoundDays = max(0, $deleteDays - $windowDays);

        $value = DB::selectValue(
            'select count(*)
             from users
             where active = 0
               and active_changed_at is not null
               and active_changed_at <= DATE_SUB(UTC_TIMESTAMP(), INTERVAL ? DAY)
               and active_changed_at > DATE_SUB(UTC_TIMESTAMP(), INTERVAL ? DAY)',
            (string) $lowerBoundDays,
            (string) $deleteDays
        );
        return (int) ($value ?? 0);
    }
}
