package com.zioinfo.kintex.visitor.paymethod;

import com.zioinfo.kintex.auth.KintexPrincipal;
import com.zioinfo.kintex.common.ApiResponse;
import com.zioinfo.kintex.visitor.VisitorAuth;
import com.zioinfo.kintex.visitor.paymethod.PayMethodDtos.PayMethodDto;
import com.zioinfo.kintex.visitor.paymethod.PayMethodDtos.QuickPayRequest;
import com.zioinfo.kintex.visitor.paymethod.PayMethodDtos.QuickPayResultDto;
import com.zioinfo.kintex.visitor.paymethod.PayMethodDtos.RegisterRequest;
import jakarta.validation.Valid;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
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 java.util.List;

/**
 * F-B5 저장 결제수단 API — 인증(본인 소유분만). PG는 mock 재사용.
 */
@RestController
@RequestMapping("/api/visitor/pay-methods")
public class PayMethodController {

    private final PayMethodService service;

    public PayMethodController(PayMethodService service) {
        this.service = service;
    }

    @GetMapping
    public ApiResponse<List<PayMethodDto>> list(@AuthenticationPrincipal KintexPrincipal principal) {
        return ApiResponse.ok(service.list(VisitorAuth.requireUserId(principal)));
    }

    @PostMapping
    public ApiResponse<PayMethodDto> register(@AuthenticationPrincipal KintexPrincipal principal,
                                              @Valid @RequestBody RegisterRequest req) {
        return ApiResponse.ok(service.register(VisitorAuth.requireUserId(principal), req));
    }

    @PostMapping("/{id}/default")
    public ApiResponse<Void> setDefault(@AuthenticationPrincipal KintexPrincipal principal,
                                        @PathVariable String id) {
        service.setDefault(VisitorAuth.requireUserId(principal), id);
        return ApiResponse.ok(null);
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@AuthenticationPrincipal KintexPrincipal principal, @PathVariable String id) {
        service.delete(VisitorAuth.requireUserId(principal), id);
        return ApiResponse.ok(null);
    }

    /** POST /quick-pay — 저장 수단으로 빠른결제(mock PG 승인). */
    @PostMapping("/quick-pay")
    public ApiResponse<QuickPayResultDto> quickPay(@AuthenticationPrincipal KintexPrincipal principal,
                                                   @Valid @RequestBody QuickPayRequest req) {
        return ApiResponse.ok(service.quickPay(
                VisitorAuth.requireUserId(principal), req.methodId(), req.amount(), req.memo()));
    }
}
