package br.gov.sigefp.rh.api;

import br.gov.sigefp.rh.api.dto.*;
import br.gov.sigefp.rh.service.AgentService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * Controller REST para gestão de agentes.
 */
@RestController
@RequestMapping("/api/rh/agents")
@RequiredArgsConstructor
public class AgentController {

    private final AgentService agentService;

    @PostMapping
    public ResponseEntity<AgentDTO> create(@Valid @RequestBody AgentDTO dto) {
        AgentDTO created = agentService.create(dto);
        return ResponseEntity.status(HttpStatus.CREATED).body(created);
    }

    @PutMapping("/{id}")
    public ResponseEntity<AgentDTO> update(
            @PathVariable("id") UUID id,
            @Valid @RequestBody AgentDTO dto) {
        AgentDTO updated = agentService.update(id, dto);
        return ResponseEntity.ok(updated);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable("id") UUID id) {
        agentService.delete(id);
        return ResponseEntity.noContent().build();
    }

    @GetMapping("/{id}")
    public ResponseEntity<AgentDTO> findById(@PathVariable("id") UUID id) {
        AgentDTO dto = agentService.findById(id);
        return ResponseEntity.ok(dto);
    }

    @GetMapping
    public ResponseEntity<Page<AgentDTO>> findAll(
            @RequestParam(value = "query", required = false) String query,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "ministry", required = false) UUID ministry,
            @RequestParam(value = "orgUnit", required = false) UUID orgUnit,
            @RequestParam(value = "position", required = false) UUID position,
            @RequestParam(value = "functionalSituation", required = false) String functionalSituation,
            @RequestParam(value = "appointmentType", required = false) String appointmentType,
            @RequestParam(value = "page", defaultValue = "0") int page,
            @RequestParam(value = "size", defaultValue = "20") int size,
            @RequestParam(value = "sortBy", required = false) String sortBy,
            @RequestParam(value = "sortDirection", required = false, defaultValue = "ASC") String sortDirection) {

        Sort sort = sortBy != null
                ? Sort.by(Sort.Direction.fromString(sortDirection), sortBy)
                : Sort.by(Sort.Direction.ASC, "createdAt");

        Pageable pageable = PageRequest.of(page, size, sort);
        Page<AgentDTO> result = agentService.findAllWithFilters(
                query, status, ministry, orgUnit, position, functionalSituation, appointmentType, pageable);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/stats")
    public ResponseEntity<AgentStatsDTO> getStats(
            @RequestParam(value = "query", required = false) String query,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "ministry", required = false) UUID ministry,
            @RequestParam(value = "orgUnit", required = false) UUID orgUnit,
            @RequestParam(value = "position", required = false) UUID position,
            @RequestParam(value = "functionalSituation", required = false) String functionalSituation,
            @RequestParam(value = "appointmentType", required = false) String appointmentType) {
        System.err.println("************************************************************");
        System.err.println("API STATS REQUEST RECEIVED");
        System.err.println("Ministry: " + ministry);
        System.err.println("OrgUnit: " + orgUnit);
        System.err.println("Query: " + query);
        System.err.println("************************************************************");
        return ResponseEntity.ok(agentService.getStats(query, status, ministry, orgUnit, position, functionalSituation,
                appointmentType));
    }

    @GetMapping("/{id}/history")
    public ResponseEntity<List<CareerTimelineDTO>> getHistory(@PathVariable("id") UUID id) {
        return ResponseEntity.ok(agentService.getTimeline(id));
    }

    @GetMapping("/{id}/status-history")
    public ResponseEntity<List<AgentStatusHistoryDTO>> getStatusHistory(@PathVariable("id") UUID id) {
        return ResponseEntity.ok(agentService.getStatusHistory(id));
    }
}
