package de.oaa.xxx.aufgaben.controller;

import de.oaa.xxx.aufgaben.Favorit;
import de.oaa.xxx.aufgaben.FavoritList;
import de.oaa.xxx.aufgaben.entity.FavoritEntity;
import de.oaa.xxx.aufgaben.repository.FavoritRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
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.List;
import java.util.UUID;

@RestController
@RequestMapping("/favorit")
@Transactional
public class FavoritController {

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

    private final FavoritRepository favoritRepository;

    public FavoritController(FavoritRepository favoritRepository) {
        this.favoritRepository = favoritRepository;
    }

    @GetMapping("/{favoritId}")
    public ResponseEntity<Favorit> get(@PathVariable UUID favoritId) {
        return favoritRepository.findById(favoritId)
                .map(entity -> ResponseEntity.ok(entity.toFavorit()))
                .orElse(ResponseEntity.noContent().build());
    }

    @GetMapping
    public ResponseEntity<FavoritList> all() {
        UUID userId = (UUID) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<FavoritEntity> entities = favoritRepository.findByUserId(userId);
        FavoritList result = new FavoritList();
        result.setFavoriten(entities.stream().map(FavoritEntity::toFavorit).toList());
        return ResponseEntity.ok(result);
    }

    @PostMapping
    public ResponseEntity<Void> create(@RequestBody Favorit favorit) {
        UUID userId = (UUID) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (favorit.getAufgabenGruppeId() == null) {
            return ResponseEntity.badRequest().build();
        }
        List<FavoritEntity> existing = favoritRepository.findByUserIdAndAufgabenGruppeId(userId, favorit.getAufgabenGruppeId());
        FavoritEntity entity;
        if (existing.isEmpty()) {
            entity = FavoritEntity.fromFavorit(favorit, userId);
            favoritRepository.save(entity);
        } else {
            entity = existing.get(0);
        }
        return ResponseEntity.created(
                ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(entity.getFavoritId()).toUri()
        ).build();
    }

    @DeleteMapping
    public ResponseEntity<Void> delete(@RequestBody Favorit favorit) {
        try {
            UUID userId = (UUID) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            favoritRepository.findByUserIdAndAufgabenGruppeId(userId, favorit.getAufgabenGruppeId())
                    .forEach(favoritRepository::delete);
            return ResponseEntity.accepted().build();
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
            return ResponseEntity.internalServerError().build();
        }
    }
}
