package sn.ladoum.bergerie.controller;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import sn.ladoum.bergerie.dto.TransfertDto;
import sn.ladoum.bergerie.service.TransfertService;

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

@RestController
@RequestMapping("/transferts")
@RequiredArgsConstructor
public class TransfertController {

    private final TransfertService transfertService;

    @GetMapping
    public List<TransfertDto> getAll() {
        return transfertService.mesTransferts();
    }

    @GetMapping("/entrants")
    public List<TransfertDto> entrants() {
        return transfertService.entrants();
    }

    @GetMapping("/sortants")
    public List<TransfertDto> sortants() {
        return transfertService.sortants();
    }

    @GetMapping("/historique/{moutonId}")
    public List<TransfertDto> historique(@PathVariable Long moutonId) {
        return transfertService.historiqueDuMouton(moutonId);
    }

    /** Historique public — accessible à tout utilisateur authentifié (fiche publique / QR). */
    @GetMapping("/historique/{moutonId}/public")
    public List<TransfertDto> historiquePublic(@PathVariable Long moutonId) {
        return transfertService.historiquePublic(moutonId);
    }

    @PostMapping
    @PreAuthorize("hasAnyRole('ADMIN','ELEVEUR')")
    @ResponseStatus(HttpStatus.CREATED)
    public TransfertDto initier(@Valid @RequestBody TransfertDto dto) {
        return transfertService.initier(dto);
    }

    @PostMapping("/{id}/accepter")
    @PreAuthorize("hasAnyRole('ADMIN','ELEVEUR')")
    public TransfertDto accepter(@PathVariable Long id) {
        return transfertService.accepter(id);
    }

    @PostMapping("/{id}/refuser")
    @PreAuthorize("hasAnyRole('ADMIN','ELEVEUR')")
    public TransfertDto refuser(@PathVariable Long id, @RequestBody(required = false) Map<String, String> body) {
        String motif = body != null ? body.get("motif") : null;
        return transfertService.refuser(id, motif);
    }

    @PostMapping("/{id}/annuler")
    @PreAuthorize("hasAnyRole('ADMIN','ELEVEUR')")
    public TransfertDto annuler(@PathVariable Long id) {
        return transfertService.annuler(id);
    }
}
