package org.raddatz.familienarchiv.tag;

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

import org.raddatz.familienarchiv.tag.MergeTagDTO;
import org.raddatz.familienarchiv.tag.TagTreeNodeDTO;
import org.raddatz.familienarchiv.tag.TagUpdateDTO;
import org.raddatz.familienarchiv.tag.Tag;
import org.raddatz.familienarchiv.security.Permission;
import org.raddatz.familienarchiv.security.RequirePermission;
import org.raddatz.familienarchiv.document.DocumentService;
import org.raddatz.familienarchiv.tag.TagService;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import jakarta.validation.Valid;

import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/api/tags")
@RequiredArgsConstructor
public class TagController {

    private final TagService tagService;
    private final DocumentService documentService;

    @PutMapping("/{id}")
    @RequirePermission(Permission.ADMIN_TAG)
    public ResponseEntity<Tag> updateTag(@PathVariable UUID id, @RequestBody TagUpdateDTO dto) {
        return ResponseEntity.ok(tagService.update(id, dto));
    }

    @DeleteMapping("/{id}")
    @RequirePermission(Permission.ADMIN_TAG)
    public ResponseEntity<Void> deleteTag(@PathVariable UUID id) {
        documentService.deleteTagCascading(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping
    public List<Tag> searchTags(@RequestParam(defaultValue = "") String query) {
        return tagService.search(query);
    }

    @GetMapping("/tree")
    public List<TagTreeNodeDTO> getTagTree() {
        return tagService.getTagTree();
    }

    @PostMapping("/{id}/merge")
    @RequirePermission(Permission.ADMIN_TAG)
    public ResponseEntity<Tag> mergeTag(@PathVariable UUID id, @Valid @RequestBody MergeTagDTO dto) {
        return ResponseEntity.ok(tagService.mergeTags(id, dto.targetId()));
    }

    @DeleteMapping("/{id}/subtree")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    @RequirePermission(Permission.ADMIN_TAG)
    public void deleteSubtree(@PathVariable UUID id) {
        tagService.deleteWithDescendants(id);
    }
}
