package com.cameleer.server.app.controller;

import com.cameleer.server.app.dto.ThresholdConfigRequest;
import com.cameleer.server.core.admin.AuditCategory;
import com.cameleer.server.core.admin.AuditResult;
import com.cameleer.server.core.admin.AuditService;
import com.cameleer.server.core.admin.ThresholdConfig;
import com.cameleer.server.core.admin.ThresholdRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/admin/thresholds")
@PreAuthorize("hasRole('ADMIN')")
@Tag(name = "Threshold Admin", description = "Monitoring threshold configuration (ADMIN only)")
public class ThresholdAdminController {

    private final ThresholdRepository thresholdRepository;
    private final AuditService auditService;

    public ThresholdAdminController(ThresholdRepository thresholdRepository, AuditService auditService) {
        this.thresholdRepository = thresholdRepository;
        this.auditService = auditService;
    }

    @GetMapping
    @Operation(summary = "Get current threshold configuration")
    public ResponseEntity<ThresholdConfig> getThresholds() {
        ThresholdConfig config = thresholdRepository.find().orElse(ThresholdConfig.defaults());
        return ResponseEntity.ok(config);
    }

    @PutMapping
    @Operation(summary = "Update threshold configuration")
    public ResponseEntity<ThresholdConfig> updateThresholds(@Valid @RequestBody ThresholdConfigRequest request,
                                                             HttpServletRequest httpRequest) {
        List<String> errors = request.validate();
        if (!errors.isEmpty()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, String.join("; ", errors));
        }

        ThresholdConfig config = request.toConfig();
        thresholdRepository.save(config, null);
        auditService.log("update_thresholds", AuditCategory.CONFIG, "thresholds",
                Map.of("config", config), AuditResult.SUCCESS, httpRequest);
        return ResponseEntity.ok(config);
    }
}
