<?php

declare(strict_types=1);

namespace PortalPeople\mail\services;

use backend\models\Mailqueue;

/**
 * MailQueueService
 *
 * Queries the mail queue for status information.
 * Extracted from api/modules/v1/controllers/NgaugeController::actionPendingMail().
 */
class MailQueueService
{
    /**
     * Return the count of pending (unsent) messages.
     *
     * A message is considered pending when:
     * - success = false
     * - status = 'Active'
     * - to_email is not empty/null
     * - attempts is null OR < 4 (not yet exhausted retries)
     * - send_after is null OR <= now (not scheduled for the future)
     *
     * @return int|string
     */
    public function pendingCount(): int|string
    {
        return Mailqueue::find()
            ->where(['=', 'success', false])
            ->andWhere(['=', 'status', 'Active'])
            ->andWhere(['not', ['to_email' => ['', null]]])
            ->andWhere(['or', ['is', 'attempts', null], ['<', 'attempts', 4]])
            ->andWhere(['or', ['is', 'send_after', null], ['<=', 'send_after', date('Y-m-d H:i:s')]])
            ->orderBy(['success' => SORT_DESC])
            ->count();
    }
}
