package de.oaa.xxx.games.bdsm.controller;

import de.oaa.xxx.games.common.aufgaben.Finisher;
import de.oaa.xxx.games.common.aufgaben.Toy;
import de.oaa.xxx.games.common.entity.AufgabenGruppeEntity;
import de.oaa.xxx.games.common.entity.FinisherEntity;
import de.oaa.xxx.games.common.entity.ToyEntity;
import de.oaa.xxx.games.common.repository.AufgabenGruppeRepository;
import de.oaa.xxx.games.common.repository.FinisherRepository;
import de.oaa.xxx.games.common.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.PutMapping;
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.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/finisher")
@Transactional
public class FinisherController {

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

    private final FinisherRepository finisherRepository;
    private final AufgabenGruppeRepository gruppeRepository;
    private final ToyRepository toyRepository;

    public FinisherController(FinisherRepository finisherRepository,
                               AufgabenGruppeRepository gruppeRepository,
                               ToyRepository toyRepository) {
        this.finisherRepository = finisherRepository;
        this.gruppeRepository = gruppeRepository;
        this.toyRepository = toyRepository;
    }

    @GetMapping("/{finisherId}")
    public ResponseEntity<Finisher> get(@PathVariable("finisherId") UUID finisherId) {
        return finisherRepository.findById(finisherId)
                .map(entity -> ResponseEntity.ok(entity.toFinisher()))
                .orElse(ResponseEntity.noContent().build());
    }

    @PostMapping
    public ResponseEntity<Void> create(@RequestBody Finisher finisher) {
        if (finisher.getKurzText() == null || finisher.getText() == null
                || finisher.getGeschlecht() == null || finisher.getGruppeId() == null) {
            return ResponseEntity.badRequest().build();
        }
        AufgabenGruppeEntity gruppeEntity = gruppeRepository.findById(finisher.getGruppeId()).orElse(null);
        if (gruppeEntity == null) {
            return ResponseEntity.badRequest().build();
        }
        if (gruppeEntity.getFinisher().size() >= 100) {
            return ResponseEntity.status(409).build();
        }
        List<ToyEntity> toys = resolveToys(finisher.getBenoetigteToys());
        FinisherEntity entity = FinisherEntity.create(finisher, gruppeEntity, toys);
        finisherRepository.save(entity);
        LOGGER.debug("Finisher {} '{}' in Gruppe {} erstellt", entity.getFinisherId(), entity.getKurzText(), finisher.getGruppeId());
        return ResponseEntity.created(
                ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(entity.getFinisherId()).toUri()
        ).build();
    }

    @PutMapping("/{finisherId}")
    public ResponseEntity<Void> update(@PathVariable("finisherId") UUID finisherId, @RequestBody Finisher finisher) {
        if (finisher.getKurzText() == null || finisher.getText() == null || finisher.getGeschlecht() == null) {
            return ResponseEntity.badRequest().build();
        }
        FinisherEntity entity = finisherRepository.findById(finisherId).orElse(null);
        if (entity == null) return ResponseEntity.notFound().build();
        entity.setKurzText(finisher.getKurzText());
        entity.setText(finisher.getText());
        entity.setGeschlecht(finisher.getGeschlecht());
        entity.setBenoetigtAktiv(finisher.getBenoetigtAktiv());
        entity.setBenoetigtPassiv(finisher.getBenoetigtPassiv());
        entity.setBenoetigteToys(resolveToys(finisher.getBenoetigteToys()));
        finisherRepository.save(entity);
        LOGGER.debug("Finisher {} aktualisiert", finisherId);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping
    public ResponseEntity<Void> delete(@RequestBody Finisher finisher) {
        try {
            finisherRepository.findById(finisher.getFinisherId()).ifPresent(finisherRepository::delete);
            return ResponseEntity.accepted().build();
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
            return ResponseEntity.internalServerError().build();
        }
    }

    private List<ToyEntity> resolveToys(List<Toy> toys) {
        if (toys == null || toys.isEmpty()) return new ArrayList<>();
        List<UUID> ids = toys.stream()
                .filter(t -> t.getToyId() != null)
                .map(Toy::getToyId)
                .toList();
        if (ids.isEmpty()) return new ArrayList<>();
        return toyRepository.findAllById(ids);
    }
}
