package de.oaa.xxx.aufgaben.controller;

import de.oaa.xxx.aufgaben.Toy;
import de.oaa.xxx.aufgaben.entity.AufgabenGruppeEntity;
import de.oaa.xxx.aufgaben.entity.ToyEntity;
import de.oaa.xxx.aufgaben.repository.AufgabenGruppeRepository;
import de.oaa.xxx.aufgaben.repository.ToyRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.util.UUID;

@RestController
@RequestMapping("/toy")
@Transactional
public class ToyController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ToyController.class);

    private final ToyRepository toyRepository;
    private final AufgabenGruppeRepository gruppeRepository;

    public ToyController(ToyRepository toyRepository, AufgabenGruppeRepository gruppeRepository) {
        this.toyRepository = toyRepository;
        this.gruppeRepository = gruppeRepository;
    }

    @GetMapping("/{toyId}")
    public ResponseEntity<Toy> get(@PathVariable UUID toyId) {
        return toyRepository.findById(toyId)
                .map(entity -> ResponseEntity.ok(entity.toToy()))
                .orElse(ResponseEntity.noContent().build());
    }

    @PostMapping
    public ResponseEntity<Void> create(@RequestBody Toy toy) {
        if (toy.getName() == null || toy.getGruppeId() == null) {
            return ResponseEntity.badRequest().build();
        }
        AufgabenGruppeEntity gruppeEntity = gruppeRepository.findById(toy.getGruppeId()).orElse(null);
        if (gruppeEntity == null || gruppeEntity.getAufgaben().size() > 50) {
            return ResponseEntity.badRequest().build();
        }
        ToyEntity entity = ToyEntity.create(toy, gruppeEntity);
        toyRepository.save(entity);
        return ResponseEntity.created(
                ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(entity.getToyId()).toUri()
        ).build();
    }

    @DeleteMapping
    @Transactional
    public ResponseEntity<Void> delete(@RequestBody Toy toy) {
        // Bug fix: original code had transaction.rollback() here - now correctly uses @Transactional
        try {
            toyRepository.findById(toy.getToyId()).ifPresent(toyRepository::delete);
            return ResponseEntity.accepted().build();
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
            return ResponseEntity.internalServerError().build();
        }
    }
}
