package org.raddatz.familienarchiv.geschichte;

import lombok.RequiredArgsConstructor;
import org.raddatz.familienarchiv.geschichte.GeschichteUpdateDTO;
import org.raddatz.familienarchiv.geschichte.Geschichte;
import org.raddatz.familienarchiv.geschichte.GeschichteStatus;
import org.raddatz.familienarchiv.security.Permission;
import org.raddatz.familienarchiv.security.RequirePermission;
import org.raddatz.familienarchiv.geschichte.GeschichteService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/geschichten")
@RequiredArgsConstructor
public class GeschichteController {

    private final GeschichteService geschichteService;

    @GetMapping
    public List<Geschichte> list(
            @RequestParam(required = false) GeschichteStatus status,
            @RequestParam(name = "personId", required = false) List<UUID> personIds,
            @RequestParam(required = false) UUID documentId,
            @RequestParam(required = false, defaultValue = "50") int limit) {
        return geschichteService.list(
                status,
                personIds == null ? List.of() : personIds,
                documentId,
                limit);
    }

    @GetMapping("/{id}")
    public Geschichte getById(@PathVariable UUID id) {
        return geschichteService.getById(id);
    }

    @PostMapping
    @RequirePermission(Permission.BLOG_WRITE)
    public ResponseEntity<Geschichte> create(@RequestBody GeschichteUpdateDTO dto) {
        Geschichte created = geschichteService.create(dto);
        return ResponseEntity.status(HttpStatus.CREATED).body(created);
    }

    @PatchMapping("/{id}")
    @RequirePermission(Permission.BLOG_WRITE)
    public Geschichte update(@PathVariable UUID id, @RequestBody GeschichteUpdateDTO dto) {
        return geschichteService.update(id, dto);
    }

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