<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Database;

final class WebhookEventModel
{
    public function record(string $provider, ?string $eventType, array $payload): int
    {
        $stmt = Database::connection()->prepare(
            'INSERT INTO webhook_events (provider, event_type, payload, received_at) VALUES (:provider, :type, :payload, NOW())'
        );
        $stmt->execute(['provider' => $provider, 'type' => $eventType, 'payload' => json_encode($payload)]);

        return (int) Database::connection()->lastInsertId();
    }

    public function markProcessed(int $id): void
    {
        Database::connection()->prepare('UPDATE webhook_events SET processed = 1 WHERE id = :id')->execute(['id' => $id]);
    }

    public function markFailed(int $id, string $error): void
    {
        Database::connection()->prepare('UPDATE webhook_events SET processed = 0, error_message = :err WHERE id = :id')
            ->execute(['id' => $id, 'err' => substr($error, 0, 500)]);
    }

    public function recent(?string $provider = null, int $limit = 100): array
    {
        $sql = 'SELECT * FROM webhook_events';
        $bindings = [];

        if ($provider !== null) {
            $sql .= ' WHERE provider = :provider';
            $bindings['provider'] = $provider;
        }
        $sql .= ' ORDER BY received_at DESC LIMIT :limit';

        $stmt = Database::connection()->prepare($sql);
        foreach ($bindings as $k => $v) {
            $stmt->bindValue($k, $v);
        }
        $stmt->bindValue('limit', $limit, \PDO::PARAM_INT);
        $stmt->execute();

        return $stmt->fetchAll();
    }
}
