<?php

declare(strict_types=1);

namespace ApiModel\Infrastructure\Persistence\Repositories;

use ApiModel\Domain\Repository\PlatformAuditRepositoryInterface;
use PDO;

final class PdoPlatformAuditRepository implements PlatformAuditRepositoryInterface
{
    public function __construct(private readonly PDO $pdo) {}

    public function log(string $action, ?string $actorUserId, ?string $targetUserId, string $metadata): void
    {
        $this->pdo->prepare(
            'INSERT INTO auth.logs (action, actor_user_id, target_id, metadata, ip_address, user_agent) VALUES (?,?,?,?,?,?)',
        )->execute([
            $action, 
            $actorUserId, 
            $targetUserId, 
            $metadata,
            $_SERVER['REMOTE_ADDR'] ?? null,
            $_SERVER['HTTP_USER_AGENT'] ?? null
        ]);
    }

    public function countAll(): int
    {
        return (int) $this->pdo->query('SELECT COUNT(*) FROM auth.logs')->fetchColumn();
    }

    public function listPage(int $limit, int $offset): array
    {
        $st = $this->pdo->prepare(
            'SELECT p.*, p.target_id AS target_user_id, u.name AS actor_name, u.email AS actor_email 
             FROM auth.logs p LEFT JOIN auth.users u ON u.id = p.actor_user_id 
             ORDER BY p.created_at DESC LIMIT ? OFFSET ?',
        );
        $st->execute([$limit, $offset]);

        return $st->fetchAll();
    }

    public function listUsersWithLatestLogin(): array
    {
        $sql = '
            SELECT u.id, u.name, u.email, MAX(l.created_at) as login
            FROM auth.users u
            LEFT JOIN auth.logs l ON l.actor_user_id = u.id AND l.action = \'USER_LOGIN\'
            GROUP BY u.id, u.name, u.email
            ORDER BY login DESC
        ';
        $st = $this->pdo->query($sql);
        return $st->fetchAll();
    }

    public function listDetailsForUser(string $userId): array
    {
        $st = $this->pdo->prepare('
            SELECT * FROM auth.logs 
            WHERE actor_user_id = ? OR target_id = ?
            ORDER BY created_at DESC
        ');
        $st->execute([$userId, $userId]);
        return $st->fetchAll();
    }
}
