package com.caliverse.admin.domain.service;

import com.caliverse.admin.global.common.constants.DynamoDBConstants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.*;

import java.time.Instant;
import java.util.List;


@Service
public class DynamoDBMetricsService {

    @Value("${amazon.dynamodb.metaTable}")
    private String metaTable;

    private final CloudWatchClient cloudWatchClient;

    public DynamoDBMetricsService(CloudWatchClient cloudWatchClient) {
        this.cloudWatchClient = cloudWatchClient;
    }

    public GetMetricDataResponse getConsumedCapacityData(Instant startTime, Instant endTime) {
        var readCapacityQuery = MetricDataQuery.builder()
                .id("readCapacity")
                .metricStat(MetricStat.builder()
                        .metric(Metric.builder()
                                .namespace(DynamoDBConstants.NAMESPACE)
                                .metricName(DynamoDBConstants.CONSUMED_READ_CAPACITY)
                                .dimensions(List.of(
                                        Dimension.builder()
                                                .name("TableName")
                                                .value(metaTable)
                                                .build()
                                ))
                                .build())
                        .period(300) // 5분 간격
                        .stat("Sum")
                        .build())
                .returnData(true)
                .build();

        var writeCapacityQuery = MetricDataQuery.builder()
                .id("writeCapacity")
                .metricStat(MetricStat.builder()
                        .metric(Metric.builder()
                                .namespace(DynamoDBConstants.NAMESPACE)
                                .metricName(DynamoDBConstants.CONSUMED_WRITE_CAPACITY)
                                .dimensions(List.of(
                                        Dimension.builder()
                                                .name("TableName")
                                                .value(metaTable)
                                                .build()
                                ))
                                .build())
                        .period(300)
                        .stat("Sum")
                        .build())
                .returnData(true)
                .build();

        var request = GetMetricDataRequest.builder()
                .startTime(startTime)
                .endTime(endTime)
                .metricDataQueries(List.of(readCapacityQuery, writeCapacityQuery))
                .build();

        return cloudWatchClient.getMetricData(request);
    }
}
