import { MembershipService } from './../membership/membership.service'
import { Injectable } from '@nestjs/common'
import { Attach, AttachType } from '../weixin/dto/attach.dto'
import { WeixinService } from '../weixin/weixin.service'
import { PayMethod } from '../membership/entities/member-order.entity'

@Injectable()
export class NotifyService {
    constructor(private readonly weixinService: WeixinService, private readonly membershipService: MembershipService) {}

    public async handleWeixinNotify(headers, body: WechatPay.NotifyEvent) {
        const data: WechatPay.NotifyData = await this.weixinService.getNotifyData(headers, body)
        if (data.trade_state === 'SUCCESS') {
            if (!data.attach) return
            const attach: Attach = JSON.parse(data.attach)
            if (attach.type === AttachType.MEMBER_ORDER) {
                await this.membershipService.orderNotify(attach.id, data.transaction_id, PayMethod.WECHAT)
            }
        }
    }
}
