NEXT_PUBLIC_SELCOM_API_KEY=FAIC24-lbasEfksJKTVskaW
NEXT_PUBLIC_SELCOM_API_SECRET=rdzWezgtV5TQZOrLatD2JFpFbMDxXVbG
NEXT_PUBLIC_SELCOM_VENDOR=TILL61048633
NEXT_PUBLIC_SELCOM_ENDPOINT=https://apigw.selcommobile.com


const webhook = btoa(process.env.NEXT_PUBLIC_WEBHOOK_URL || '');
const redirect = btoa(process.env.NEXT_PUBLIC_REDIRECT_URL || '');
const apiKey = process.env.NEXT_PUBLIC_SELCOM_API_KEY || '';
const apiSecret = process.env.NEXT_PUBLIC_SELCOM_API_SECRET || '';
const vendor = process.env.NEXT_PUBLIC_SELCOM_VENDOR || '';
const baseUrl = process.env.NEXT_PUBLIC_SELCOM_ENDPOINT || '';

const client = new SelcomPay(baseUrl, apiKey, apiSecret, vendor);

let selcomResponse: any = {};
let redirectUrl = '';

if (
    dto.registrationPaymentDuration === 'payNow' &&
    dto.paymentOption === PaymentMethod.Mobile
) {
    const orderJson = {
    vendor,
    order_id: reference,
    buyer_email: dto.email,
    buyer_name: dto.fullName,
    buyer_phone: dto.phoneNumber,
    amount: amount,
    currency: dto.currency,
    buyer_remarks: 'None',
    merchant_remarks: 'None',
    no_of_items: 1,
    webhook
    };

    console.info({ orderJson });

    const orderPath = '/v1/checkout/create-order-minimal';
    const walletPaymentPath = '/v1/checkout/wallet-payment';

    selcomResponse = await client.post(orderPath, orderJson);



    
    if (selcomResponse.result === 'SUCCESS') {
    const walletPaymentJson = {
        transid: reference,
        order_id: reference,
        msisdn: dto.phoneNumber
    };
    await client.post(walletPaymentPath, walletPaymentJson);
    }

    if (selcomResponse.result === 'SUCCESS')
    redirectUrl = atob(selcomResponse?.data[0]?.payment_gateway_url);
}

if (
    dto.registrationPaymentDuration === 'payNow' &&
    dto.paymentOption === PaymentMethod.Card
) {
    const orderPath = '/v1/checkout/create-order';

    const orderJson = {
    vendor,
    order_id: reference,
    buyer_email: dto.email,
    buyer_name: dto.fullName,
    buyer_phone: dto.phoneNumber,
    amount: amount,
    currency: dto.currency,
    buyer_remarks: 'None',
    merchant_remarks: 'None',
    no_of_items: 1,
    payment_methods: 'CARD',
    redirect_url: redirect,
    cancel_url: 'aHR0cHM6Ly9leGFtcGxlLmNvbS8=',
    webhook,
    'billing.firstname': dto.fullName,
    'billing.lastname': dto.fullName,
    'billing.address_1': 'Mansfield Street',
    'billing.address_2':
        'Office No.1105, 11th floor, Samora Tower Buildings',
    'billing.city': 'Dar es Salaam',
    'billing.state_or_region': 'Tanzania',
    'billing.postcode_or_pobox': '63',
    'billing.country': 'TZ',
    'billing.phone': dto.phoneNumber
    };

    console.info({ orderJson });

    selcomResponse = await client.post(orderPath, orderJson);

    if (selcomResponse.result === 'SUCCESS')
    redirectUrl = atob(selcomResponse?.data[0]?.payment_gateway_url);
}