package com.hiveops.aria.controller;

import com.hiveops.aria.entity.ThreatIoc;
import com.hiveops.aria.repository.ThreatIocRepository;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/aria/ioc")
@RequiredArgsConstructor
public class ThreatIocController {

    private final ThreatIocRepository iocRepository;

    @GetMapping
    @PreAuthorize("hasAnyRole('MSP_ADMIN','BCOS_ADMIN')")
    public List<ThreatIoc> getAll(
            @RequestParam(required = false) ThreatIoc.IocType type,
            @RequestParam(required = false, defaultValue = "true") boolean activeOnly) {

        if (type != null) {
            return activeOnly
                    ? iocRepository.findByActiveTrueAndIocType(type)
                    : iocRepository.findAll().stream().filter(i -> i.getIocType() == type).toList();
        }
        return activeOnly ? iocRepository.findByActiveTrue() : iocRepository.findAll();
    }

    @GetMapping("/active")
    public List<ThreatIoc> getActive(@RequestParam(required = false) ThreatIoc.IocType type) {
        return type != null
                ? iocRepository.findByActiveTrueAndIocType(type)
                : iocRepository.findByActiveTrue();
    }

    @PostMapping
    @PreAuthorize("hasAnyRole('MSP_ADMIN','BCOS_ADMIN')")
    public ResponseEntity<ThreatIoc> create(@Valid @RequestBody CreateIocRequest request) {
        ThreatIoc ioc = ThreatIoc.builder()
                .iocType(request.getIocType())
                .value(request.getValue())
                .description(request.getDescription())
                .source(ThreatIoc.IocSource.MANUAL)
                .sourceRef(request.getSourceRef())
                .confidence(request.getConfidence() != null ? request.getConfidence() : ThreatIoc.ConfidenceLevel.MEDIUM)
                .expiresAt(request.getExpiresAt())
                .build();
        return ResponseEntity.ok(iocRepository.save(ioc));
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasAnyRole('MSP_ADMIN','BCOS_ADMIN')")
    public ResponseEntity<ThreatIoc> update(@PathVariable Long id, @Valid @RequestBody CreateIocRequest request) {
        return iocRepository.findById(id).map(ioc -> {
            ioc.setValue(request.getValue());
            ioc.setDescription(request.getDescription());
            ioc.setConfidence(request.getConfidence() != null ? request.getConfidence() : ioc.getConfidence());
            ioc.setExpiresAt(request.getExpiresAt());
            return ResponseEntity.ok(iocRepository.save(ioc));
        }).orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyRole('MSP_ADMIN','BCOS_ADMIN')")
    public ResponseEntity<Void> deactivate(@PathVariable Long id) {
        return iocRepository.findById(id).map(ioc -> {
            ioc.setActive(false);
            iocRepository.save(ioc);
            return ResponseEntity.noContent().<Void>build();
        }).orElse(ResponseEntity.notFound().build());
    }

    @Data
    public static class CreateIocRequest {
        @NotNull
        private ThreatIoc.IocType iocType;
        @NotBlank
        private String value;
        private String description;
        private String sourceRef;
        private ThreatIoc.ConfidenceLevel confidence;
        private Instant expiresAt;
    }
}
