package com.zioinfo.mall.gateway;

import com.zioinfo.mall.common.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 게이트웨이 어댑터 API — /api/mall/gateway.
 * 세금 견적·주소 검증은 체크아웃에 필요(인증 고객). 라우팅은 MANAGER+. provider 상태는 MANAGER+.
 */
@RestController
@RequestMapping("/api/mall/gateway")
@RequiredArgsConstructor
public class GatewayController {

    private final TaxCalculator taxCalculator;
    private final AddressVerifier addressVerifier;
    private final PaymentGateway paymentGateway;
    private final SmsSender smsSender;
    private final EmailSender emailSender;

    /** 판매세 견적(체크아웃). */
    @PostMapping("/tax/quote")
    public ApiResponse<Map<String, Object>> taxQuote(@RequestBody Map<String, Object> req) {
        BigDecimal amount = new BigDecimal(String.valueOf(req.getOrDefault("amount", "0")));
        String zip = (String) req.get("zip");
        String state = (String) req.get("state");
        return ApiResponse.ok(taxCalculator.calculate(amount, zip, state));
    }

    /** 배송 주소 검증(체크아웃). */
    @PostMapping("/address/verify")
    public ApiResponse<Map<String, Object>> verify(@RequestBody Map<String, String> req) {
        return ApiResponse.ok(addressVerifier.verify(req.get("address"), req.get("zip")));
    }

    /** 기사 라우팅 — 다중 주소 최적 동선 (관리자앱 ④). */
    @PostMapping("/address/route")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    @SuppressWarnings("unchecked")
    public ApiResponse<Map<String, Object>> route(@RequestBody Map<String, Object> req) {
        List<String> addresses = (List<String>) req.getOrDefault("addresses", List.of());
        String origin = (String) req.get("origin");
        return ApiResponse.ok(addressVerifier.route(addresses, origin));
    }

    /** 활성 provider 상태(운영 점검). 키 자체는 노출하지 않음. */
    @GetMapping("/providers")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<Map<String, Object>> providers() {
        Map<String, Object> out = new LinkedHashMap<>();
        out.put("payment", paymentGateway.provider());
        out.put("tax", taxCalculator.provider());
        out.put("address", addressVerifier.provider());
        out.put("sms", smsSender.provider());
        out.put("email", emailSender.provider());
        return ApiResponse.ok(out);
    }
}
