<?php
declare(strict_types=1);
namespace App\Platform\Soc\Event;

use App\Core\Database;
use Throwable;

final class EventQueueProcessor
{
    public function __construct(private readonly EventStorage $storage = new EventStorage()) {}

    /** @return array{processed:int,failed:int} */
    public function process(int $limit = 100): array
    {
        $processed = 0;
        $failed = 0;
        foreach ($this->storage->pending($limit) as $row) {
            try {
                $payload = json_decode((string) $row['payload_json'], true, 512, JSON_THROW_ON_ERROR);
                $statement = Database::connection()->prepare(
                    'INSERT IGNORE INTO system_security_events '
                    . '(event_uuid,severity,category,module,action,result,message,user_id,organisation_id,session_reference,ip_hash,device_hash,subject_type,subject_reference,request_id,metadata_json,occurred_at,created_at) '
                    . 'VALUES (:event_uuid,:severity,:category,:module,:action,:result,:message,:user_id,:organisation_id,:session_reference,:ip_hash,:device_hash,:subject_type,:subject_reference,:request_id,:metadata_json,:occurred_at,NOW())'
                );
                $statement->execute($payload);
                $this->storage->markProcessed((int) $row['id']);
                $processed++;
            } catch (Throwable $exception) {
                $this->storage->markFailed((int) $row['id'], $exception->getMessage());
                $failed++;
            }
        }
        return ['processed'=>$processed,'failed'=>$failed];
    }
}
