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

import de.oaa.xxx.games.bdsm.entity.BdsmSetupDraftEntity;
import de.oaa.xxx.games.bdsm.repository.BdsmSetupDraftRepository;
import de.oaa.xxx.user.UserRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/bdsm/setup-draft")
@Transactional
public class BdsmSetupDraftController {

    private final BdsmSetupDraftRepository draftRepository;
    private final UserRepository userRepository;

    public BdsmSetupDraftController(BdsmSetupDraftRepository draftRepository, UserRepository userRepository) {
        this.draftRepository = draftRepository;
        this.userRepository = userRepository;
    }

    record DraftRequest(String setupId, String settingsJson, String setupJson, String gruppenJson) {}

    private UUID currentUserId(Principal principal) {
        return userRepository.findByEmail(principal.getName()).map(u -> u.getUserId()).orElse(null);
    }

    @GetMapping
    public ResponseEntity<Map<String, Object>> getDraft(
            @RequestParam(required = false) String setupId,
            Principal principal) {
        UUID userId = currentUserId(principal);
        if (userId == null) return ResponseEntity.status(401).build();
        var lookup = (setupId != null && !setupId.isBlank())
                ? draftRepository.findBySetupId(setupId)
                : draftRepository.findByUserId(userId);
        return lookup
                .map(d -> {
                    Map<String, Object> m = new LinkedHashMap<>();
                    m.put("setupId",      d.getSetupId());
                    m.put("settingsJson", d.getSettingsJson());
                    m.put("setupJson",    d.getSetupJson());
                    m.put("gruppenJson",  d.getGruppenJson());
                    return ResponseEntity.ok(m);
                })
                .orElse(ResponseEntity.noContent().build());
    }

    @PutMapping
    public ResponseEntity<Void> saveDraft(@RequestBody DraftRequest req, Principal principal) {
        UUID userId = currentUserId(principal);
        if (userId == null) return ResponseEntity.status(401).build();
        BdsmSetupDraftEntity d = draftRepository.findByUserId(userId)
                .orElseGet(() -> { BdsmSetupDraftEntity n = new BdsmSetupDraftEntity(); n.setUserId(userId); return n; });
        if (req.setupId() != null)    d.setSetupId(req.setupId());
        if (req.settingsJson() != null) d.setSettingsJson(req.settingsJson());
        if (req.setupJson() != null)  d.setSetupJson(req.setupJson());
        if (req.gruppenJson() != null) d.setGruppenJson(req.gruppenJson());
        d.setUpdatedAt(LocalDateTime.now());
        draftRepository.save(d);
        return ResponseEntity.accepted().build();
    }

    @DeleteMapping
    public ResponseEntity<Void> deleteDraft(Principal principal) {
        UUID userId = currentUserId(principal);
        if (userId == null) return ResponseEntity.status(401).build();
        draftRepository.findByUserId(userId).ifPresent(draftRepository::delete);
        return ResponseEntity.accepted().build();
    }
}
