package com.gcsc.connection.apikey.dto;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gcsc.connection.apikey.entity.SnpApiKeyRequest;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

public record ApiKeyRequestResponse(
    Long requestId,
    Long userId,
    String userName,
    String keyName,
    String purpose,
    List<Long> requestedApiIds,
    String status,
    Long reviewedByUserId,
    String reviewerName,
    String reviewComment,
    LocalDateTime reviewedAt,
    LocalDateTime createdAt,
    String serviceIp,
    String servicePurpose,
    Long dailyRequestEstimate,
    LocalDateTime usageFromDate,
    LocalDateTime usageToDate
) {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public static ApiKeyRequestResponse from(SnpApiKeyRequest request) {
        List<Long> apiIds = parseApiIds(request.getRequestedApis());
        Long reviewerUserId = request.getReviewedBy() != null
            ? request.getReviewedBy().getUserId() : null;
        String reviewerName = request.getReviewedBy() != null
            ? request.getReviewedBy().getUserName() : null;

        return new ApiKeyRequestResponse(
            request.getRequestId(),
            request.getUser().getUserId(),
            request.getUser().getUserName(),
            request.getKeyName(),
            request.getPurpose(),
            apiIds,
            request.getStatus().name(),
            reviewerUserId,
            reviewerName,
            request.getReviewComment(),
            request.getReviewedAt(),
            request.getCreatedAt(),
            request.getServiceIp(),
            request.getServicePurpose(),
            request.getDailyRequestEstimate(),
            request.getUsageFromDate(),
            request.getUsageToDate()
        );
    }

    private static List<Long> parseApiIds(String json) {
        if (json == null || json.isBlank()) {
            return Collections.emptyList();
        }
        try {
            return OBJECT_MAPPER.readValue(json, new TypeReference<>() {});
        } catch (Exception e) {
            return Collections.emptyList();
        }
    }
}
