package br.gov.sigefp.rh.api;

import br.gov.sigefp.rh.api.dto.AbsenceDTO;
import br.gov.sigefp.rh.api.dto.CreateAbsenceDTO;
import br.gov.sigefp.rh.service.AbsenceService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
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;

@RestController
@RequestMapping("/api/rh/absences")
@RequiredArgsConstructor
public class AbsenceController {

    private final AbsenceService absenceService;

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

    @GetMapping("/agent/{agentId}")
    public ResponseEntity<Page<AbsenceDTO>> findByAgent(
            @PathVariable UUID agentId,
            @RequestParam(name = "page", defaultValue = "0") int page,
            @RequestParam(name = "size", defaultValue = "20") int size,
            @RequestParam(name = "sortBy", required = false) String sortBy,
            @RequestParam(name = "sortDirection", required = false, defaultValue = "DESC") String sortDirection) {

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

        Pageable pageable = PageRequest.of(page, size, sort);
        Page<AbsenceDTO> result = absenceService.findByAgent(agentId, pageable);
        return ResponseEntity.ok(result);
    }

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