package com.hiveops.guide.controller;

import com.hiveops.guide.service.GiteaFeedbackService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/** In-guide "report a bug / suggest an enhancement" → creates a Gitea issue. Requires a logged-in user. */
@RestController
@RequestMapping("/api/v1/guide/feedback")
@RequiredArgsConstructor
public class FeedbackController {

    private final GiteaFeedbackService service;

    public record FeedbackRequest(String type, String area, String title, String description, String module) {}

    @PostMapping
    public ResponseEntity<?> submit(@RequestBody FeedbackRequest r, Authentication auth) {
        String email = auth != null ? auth.getName() : null;
        String role = auth != null
                ? auth.getAuthorities().stream().findFirst()
                    .map(a -> a.getAuthority().replaceFirst("^ROLE_", "")).orElse(null)
                : null;
        GiteaFeedbackService.Result res = service.create(
                r.type(), r.area(), r.title(), r.description(), r.module(), email, role);
        return res.success()
                ? ResponseEntity.ok(Map.of("number", res.number(), "url", res.url()))
                : ResponseEntity.badRequest().body(Map.of("error", res.error() == null ? "Failed" : res.error()));
    }
}
