using Microsoft.AspNetCore.Mvc;
using EasyPaySample.Models;
using EasyPaySample.Services;
using System.Diagnostics;

namespace EasyPaySample.Controllers
{
    public class PaymentController : Controller
    {
        private readonly EasyPayService _service;

        public PaymentController(EasyPayService service)
        {
            _service = service;
        }

        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> DoPay(string goodsName, string amount, string payMethodTypeCode)
        {
            var mallOrderNo = $"CS_{DateTime.Now:yyyyMMddHHmmss}{Random.Shared.Next(100, 999)}";
            var callbackUrl = $"{Request.Scheme}://{Request.Host}/Payment/Callback";

            var request = new TradeWebPayRequest
            {
                MallId = _service.GetMallId(),
                ShopOrderNo = mallOrderNo,
                Amount = amount,
                PayMethodTypeCode = payMethodTypeCode,
                ReturnUrl = callbackUrl,
                OrderInfo = new OrderInfo { GoodsName = goodsName }
            };

            var response = await _service.PostAsync("/api/ep9/trades/webpay", request);

            if (response?.ResCd == "0000" && !string.IsNullOrEmpty(response.AuthPageUrl))
            {
                return Redirect(response.AuthPageUrl);
            }

            return View("Failure", response ?? new EasyPayResponse { ResCd = "ERROR", ResMsg = "거래 등록 실패" });
        }

        [HttpPost]
        [HttpGet]
        public async Task<IActionResult> Callback()
        {
            // GET/POST 통합 처리
            var resCd = Request.Method == "POST" ? Request.Form["resCd"].ToString() : Request.Query["resCd"].ToString();
            var resMsg = Request.Method == "POST" ? Request.Form["resMsg"].ToString() : Request.Query["resMsg"].ToString();
            
            if (resCd != "0000")
            {
                return View("Failure", new EasyPayResponse { ResCd = resCd, ResMsg = resMsg });
            }

            var authorizationId = Request.Method == "POST" ? Request.Form["authorizationId"].ToString() : Request.Query["authorizationId"].ToString();
            var shopOrderNo = Request.Method == "POST" ? Request.Form["shopOrderNo"].ToString() : Request.Query["shopOrderNo"].ToString();

            var approvalRequest = new ApprovalRequest
            {
                MallId = _service.GetMallId(),
                ShopTransactionId = $"CS_APP_{DateTime.Now:yyyyMMddHHmmss}{Random.Shared.Next(100, 999)}",
                AuthorizationId = authorizationId,
                ShopOrderNo = shopOrderNo,
                ApprovalReqDate = DateTime.Now.ToString("yyyyMMdd")
            };

            var response = await _service.PostAsync("/api/ep9/trades/approval", approvalRequest);

            if (response?.ResCd == "0000")
            {
                return View("Success", response);
            }

            return View("Failure", response ?? new EasyPayResponse { ResCd = "ERROR", ResMsg = "승인 처리 실패" });
        }

        [HttpPost]
        public async Task<IActionResult> DoCancel(string pgCno)
        {
            var shopTransactionId = $"CS_CAN_{DateTime.Now:yyyyMMddHHmmss}{Random.Shared.Next(100, 999)}";
            var cancelReqDate = DateTime.Now.ToString("yyyyMMdd");

            // HMAC 검증값 생성: pgCno | shopTransactionId
            var authStr = $"{pgCno}|{shopTransactionId}";
            var msgAuthValue = _service.GetHmac(authStr);

            var request = new ReviseRequest
            {
                MallId = _service.GetMallId(),
                ShopTransactionId = shopTransactionId,
                CancelReqDate = cancelReqDate,
                PgCno = pgCno,
                MsgAuthValue = msgAuthValue
            };

            var response = await _service.PostAsync("/api/trades/revise", request);

            if (response?.ResCd == "0000")
            {
                return View("CancelSuccess", response);
            }

            return View("Failure", response ?? new EasyPayResponse { ResCd = "ERROR", ResMsg = "취소 처리 실패" });
        }
    }
}
