<?php

declare(strict_types=1);

namespace ApiModel\Service;

use ApiModel\Domain\Repository\PlatformAuditRepositoryInterface;

final class AuditLogService
{
    public function __construct(
        private readonly PlatformAuditRepositoryInterface $platformAudit
    ) {}

    /** @return list<array<string, mixed>> */
    public function listUsersLogsSummary(): array
    {
        return $this->platformAudit->listUsersWithLatestLogin();
    }

    /** @return list<array<string, mixed>> */
    public function listLogsForUser(string $userId): array
    {
        $rows = $this->platformAudit->listDetailsForUser($userId);
        $out = [];
        foreach ($rows as $r) {
            $meta = json_decode((string) ($r['metadata'] ?? '{}'), true) ?: [];

            $out[] = [
                'created_at' => $r['created_at'],
                'event_type' => $this->resolveEventType($r, $meta),
                'class' => $meta['class'] ?? '',
                'method' => $meta['method'] ?? '',
                'request' => $meta['request'] ?? $r['action'],
                'status' => $meta['status'] ?? 200,
                'agent' => $r['user_agent'] ?? $meta['agent'] ?? '',
                'screen' => $meta['screen'] ?? '',
                'leng' => $meta['leng'] ?? 'es',
                'ip_address' => $r['ip_address'] ?? '',
                'record_id' => $r['target_id'] ?? '',
                'message' => $meta['message'] ?? $r['action']
            ];
        }

        return $out;
    }

    /** @param array<string, mixed> $row @param array<string, mixed> $meta */
    private function resolveEventType(array $row, array $meta): string
    {
        $action = (string) ($row['action'] ?? '');

        if (str_starts_with($action, 'USER_') || str_starts_with($action, 'PASSWORD_')) {
            return $action;
        }

        if ($action === 'API_REQUEST' && isset($meta['method']) && is_string($meta['method'])) {
            return $meta['method'];
        }

        if (isset($meta['method']) && is_string($meta['method'])) {
            return $meta['method'];
        }

        return $action;
    }
}
