package br.gov.sigefp.org.api;

import br.gov.sigefp.org.api.dto.MinistryDTO;
import br.gov.sigefp.org.service.MinistryService;
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;

/**
 * Controller REST para gestão de ministérios.
 */
@RestController
@RequestMapping("/api/org/ministries")
@RequiredArgsConstructor
public class MinistryController {

    private final MinistryService ministryService;

    @GetMapping
    public ResponseEntity<Page<MinistryDTO>> findAll(
            @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, "code");
        
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<MinistryDTO> result = ministryService.findAll(pageable);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/{id}")
    public ResponseEntity<MinistryDTO> findById(@PathVariable("id") UUID id) {
        try {
            MinistryDTO dto = ministryService.findById(id);
            return ResponseEntity.ok(dto);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping
    public ResponseEntity<MinistryDTO> create(@Valid @RequestBody MinistryDTO dto) {
        try {
            MinistryDTO created = ministryService.create(dto);
            return ResponseEntity.status(HttpStatus.CREATED).body(created);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<MinistryDTO> update(
            @PathVariable("id") UUID id,
            @Valid @RequestBody MinistryDTO dto) {
        try {
            MinistryDTO updated = ministryService.update(id, dto);
            return ResponseEntity.ok(updated);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable("id") UUID id) {
        try {
            ministryService.delete(id);
            return ResponseEntity.noContent().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }
}

