export default class ZarinpalV4 {

    merchant_id: string;

    constructor(merchant_id: string) {
        this.merchant_id = merchant_id;
    }

    async request(amount: number, callback_url: string, description: string = "توضیحات", mobile?: string, currency = "IRT", email?: string, order_id?: number) {

        const response = await fetch('https://api.zarinpal.com/pg/v4/payment/request.json', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify(
                {
                    merchant_id: this.merchant_id,
                    amount: amount,
                    callback_url: callback_url,
                    currency: currency,
                    description: description,
                    metadata: {
                        mobile: mobile,
                        email: email,
                        order_id: order_id
                    }
                }
            )
        });

        var data = await response.json();
        data.url = "https://www.zarinpal.com/pg/StartPay/" + data.authority;

        const result: {
            data: {
                authority: string,
                fee: number,
                fee_type: string,
                code: number,
                message: string
            },
            url: string,
            error: any
        } = data;

        return result;
    }

    async verify(amount: number, authority_code: string) {

        const response = await fetch('https://api.zarinpal.com/pg/v4/payment/verify.json', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify(
                {
                    merchant_id: this.merchant_id,
                    amount: amount,
                    authority: authority_code
                })
        });

        var data = await response.json();

        return data;
    }
}