import { Context } from "koa";
import {
  ChannelHandler,
  LoginResult,
  PaymentResult,
} from "../interfaces/ChannelHandler";
import { ChannelConfig } from "../../config/channelConfig";
import { PaymentHelper } from "../../utils/PaymentHelper";
import { SignatureVerifier } from "../../utils/SignatureVerifier";
const logger = require("../../utils/log");

export class FourThreeNineNineChannelHandler implements ChannelHandler {
  async handleLogin(ctx: Context, config: ChannelConfig): Promise<LoginResult> {
    const data = ctx.request.body as any;
    logger.info("4399登录请求参数:", { data });

    const secondsTimestamp = Math.floor(Date.now() / 1000);

    if (secondsTimestamp - data.time > 5 * 60) {
      return {
        code: 0,
        msg: "超过5分钟有效时间",
      };
    }

    if (!SignatureVerifier.verify4399Sign(data, config.loginConfig?.callKey)) {
      return {
        code: 0,
        msg: "签名错误",
      };
    }

    return {
      code: 1,
      msg: "success",
    };
  }

  async handlePayment(
    ctx: Context,
    config: ChannelConfig
  ): Promise<PaymentResult> {
    let ret = {
      code: 0,
      msg: "发货失败",
    };

    const data = ctx.request.body as any;
    const orderId = data.mark;
    const out_trade_no = data.orderId;

    logger.info("4399支付回调参数:", { url: ctx.href, params: data });

    // 验证签名
    if (
      !SignatureVerifier.verify4399Sign(data, config.paymentConfig?.signKey)
    ) {
      logger.error("4399支付签名验证失败");
      ret.msg = "签名错误";
      ret.code = -2;
      return ret;
    }

    // 验证订单
    const validation = await PaymentHelper.validateOrder(orderId);
    if (!validation.valid) {
      return {
        code: validation.message?.includes("重复发货") ? 1 : 0,
        msg: validation.message,
      };
    }

    const orderInfo = validation.orderInfo;

    if (orderInfo.amount != data.money) {
      return {
        code: -8,
        msg: "订单金额不一致",
      };
    }

    // 发货处理
    logger.info(`4399支付订单${orderId}通知游戏发货开始`);
    const result = await PaymentHelper.deliverOrder(
      orderInfo,
      ctx.request.ip,
      validation.url,
      out_trade_no
    );
    logger.info(`4399支付订单${orderId}通知游戏发货结束，结果:`, result);

    return result;
  }
}
