<?php
declare(strict_types=1);

namespace App\Modules\Notifications\Models;

use App\Core\App;

class NotificationQueue
{
    public static function add(array $data): int
    {
        $db = App::getInstance()->db();
        return $db->insert('notification_queue', array_merge([
            'status'     => 'pending',
            'attempts'   => 0,
            'created_at' => date('Y-m-d H:i:s'),
        ], $data));
    }

    public static function getPending(int $limit = 50): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM notification_queue WHERE status = 'pending' AND attempts < max_attempts AND (scheduled_at IS NULL OR scheduled_at <= NOW()) ORDER BY priority DESC, created_at ASC LIMIT ?",
            [$limit]
        );
    }

    public static function markProcessed(int $id): void
    {
        $db = App::getInstance()->db();
        $db->update('notification_queue', ['status' => 'sent', 'processed_at' => date('Y-m-d H:i:s')], '`id` = ?', [$id]);
    }

    public static function markFailed(int $id): void
    {
        $db = App::getInstance()->db();
        $db->query("UPDATE notification_queue SET attempts = attempts + 1, status = IF(attempts + 1 >= max_attempts, 'failed', 'pending') WHERE id = ?", [$id]);
    }
}