<?php

declare(strict_types=1);

namespace ApiModel\Infrastructure\Persistence\Repositories;

use ApiModel\Domain\Repository\NotificationRepositoryInterface;
use PDO;

final class PdoNotificationRepository implements NotificationRepositoryInterface
{
    public function __construct(private readonly PDO $pdo) {}

    public function listForUser(string $userId, int $page, int $limit, bool $unreadOnly): array
    {
        $where = 'user_id = ?';
        $params = [$userId];
        if ($unreadOnly) {
            $where .= ' AND is_read = 0';
        }

        $cst = $this->pdo->prepare("SELECT COUNT(*) FROM notifications WHERE {$where}");
        $cst->execute($params);
        $total = (int) $cst->fetchColumn();

        $uc = $this->pdo->prepare('SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0');
        $uc->execute([$userId]);
        $unreadCount = (int) $uc->fetchColumn();

        $st = $this->pdo->prepare("SELECT * FROM notifications WHERE {$where} ORDER BY created_at DESC LIMIT ? OFFSET ?");
        $st->execute([...$params, $limit, ($page - 1) * $limit]);

        $data = [];
        foreach ($st->fetchAll() as $n) {
            $data[] = [
                'id' => $n['id'],
                'type' => $n['type'],
                'title' => $n['title'],
                'body' => $n['body'],
                'claim_id' => $n['claim_id'],
                'is_read' => (bool) $n['is_read'],
                'created_at' => $n['created_at'],
            ];
        }

        return ['data' => $data, 'unread_count' => $unreadCount, 'total' => $total];
    }

    public function markAllRead(string $userId): array
    {
        $this->pdo->prepare('UPDATE notifications SET is_read = 1 WHERE user_id = ?')->execute([$userId]);
        return ['updated' => true];
    }

    public function markOneRead(string $notificationId, string $userId): array
    {
        $this->pdo->prepare('UPDATE notifications SET is_read = 1 WHERE id = ? AND user_id = ?')->execute([$notificationId, $userId]);
        return ['updated' => true];
    }
}
