package com.cameleer.server.app.dto;

import com.cameleer.server.core.admin.ThresholdConfig;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;

import java.util.ArrayList;
import java.util.List;

@Schema(description = "Threshold configuration for admin monitoring")
public record ThresholdConfigRequest(
        @Valid @NotNull DatabaseThresholdsRequest database
) {

    @Schema(description = "Database monitoring thresholds")
    public record DatabaseThresholdsRequest(
            @Min(0) @Max(100)
            @Schema(description = "Connection pool usage warning threshold (percentage)")
            int connectionPoolWarning,

            @Min(0) @Max(100)
            @Schema(description = "Connection pool usage critical threshold (percentage)")
            int connectionPoolCritical,

            @Positive
            @Schema(description = "Query duration warning threshold (seconds)")
            double queryDurationWarning,

            @Positive
            @Schema(description = "Query duration critical threshold (seconds)")
            double queryDurationCritical
    ) {}

    /** Convert to core domain model */
    public ThresholdConfig toConfig() {
        return new ThresholdConfig(
                new ThresholdConfig.DatabaseThresholds(
                        database.connectionPoolWarning(),
                        database.connectionPoolCritical(),
                        database.queryDurationWarning(),
                        database.queryDurationCritical()
                )
        );
    }

    /** Validate semantic constraints beyond annotation-level validation */
    public List<String> validate() {
        List<String> errors = new ArrayList<>();

        if (database != null) {
            if (database.connectionPoolWarning() > database.connectionPoolCritical()) {
                errors.add("database.connectionPoolWarning must be <= connectionPoolCritical");
            }
            if (database.queryDurationWarning() > database.queryDurationCritical()) {
                errors.add("database.queryDurationWarning must be <= queryDurationCritical");
            }
        }

        return errors;
    }
}
