package com.smyhub.store.mengyastorebackendjava.controller;

import com.smyhub.store.mengyastorebackendjava.dto.request.CheckoutRequest;
import com.smyhub.store.mengyastorebackendjava.dto.response.ApiResponse;
import com.smyhub.store.mengyastorebackendjava.security.SproutGateUser;
import com.smyhub.store.mengyastorebackendjava.security.SproutGateVerifyResult;
import com.smyhub.store.mengyastorebackendjava.service.OrderService;
import com.smyhub.store.mengyastorebackendjava.service.SproutGateAuthService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class PublicOrderController {

    private final OrderService orderService;
    private final SproutGateAuthService authService;

    @PostMapping("/checkout")
    public ResponseEntity<ApiResponse<Map<String, Object>>> checkout(
            @Valid @RequestBody CheckoutRequest req,
            HttpServletRequest request) {

        SproutGateUser user = tryResolveUser(request);
        OrderService.CheckoutResult result = orderService.checkout(req, user);

        String qrPayload = "order:" + result.orderId() + ":" + result.productId();
        String qrUrl = "https://api.qrserver.com/v1/create-qr-code/?size=320x320&data="
                + java.net.URLEncoder.encode(qrPayload, java.nio.charset.StandardCharsets.UTF_8);

        return ResponseEntity.ok(ApiResponse.ok(Map.of(
                "orderId", result.orderId(),
                "qrCodeUrl", qrUrl,
                "productId", result.productId(),
                "productQty", result.qty(),
                "viewCount", result.viewCount(),
                "status", result.status()
        )));
    }

    @PostMapping("/orders/{id}/confirm")
    public ResponseEntity<ApiResponse<Map<String, Object>>> confirmOrder(@PathVariable String id) {
        var order = orderService.confirmOrder(id);
        return ResponseEntity.ok(ApiResponse.ok(Map.of(
                "orderId", order.getId(),
                "status", order.getStatus(),
                "deliveryMode", order.getDeliveryMode(),
                "deliveredCodes", order.getDeliveredCodes(),
                "isManual", "manual".equals(order.getDeliveryMode())
        )));
    }

    private SproutGateUser tryResolveUser(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (!StringUtils.hasText(header) || !header.startsWith("Bearer ")) return null;
        String token = header.substring(7);
        SproutGateVerifyResult result = authService.verifyToken(token);
        return (result.isValid() && result.getUser() != null) ? result.getUser() : null;
    }
}
