import crypto from 'crypto';
import { GatewaySecretConfig, ServerTransaction } from './types';

export class NagadService {
  private static getBaseUrl(config: GatewaySecretConfig): string {
    if (config.api_url && config.api_url.trim()) {
      return config.api_url.trim().replace(/\/+$/, '');
    }
    return config.mode === 'live'
      ? 'https://api.mynagad.com/api/dfs'
      : 'http://sandbox.mynagad.com:10080/remote-payment-gateway-1.0/api/dfs';
  }

  /**
   * Initialize Payment Session with Nagad
   */
  public static async initPayment(
    config: GatewaySecretConfig,
    txn: ServerTransaction,
    callbackUrl: string
  ): Promise<{ success: boolean; paymentUrl?: string; paymentRefId?: string; message?: string }> {
    const merchantId = config.merchant_id || '683002007104225';

    if (config.mode === 'live') {
      if (!config.merchant_id || !config.public_key || !config.private_key) {
        return {
          success: false,
          message: 'Nagad live credentials (Merchant ID, Public Key, Private Key) are incomplete in Admin.',
        };
      }

      try {
        const baseUrl = this.getBaseUrl(config);
        const datetime = new Date().toISOString().replace(/[-:T.Z]/g, '').slice(0, 14);

        // Step 1: Initialize
        const initPayload = {
          dateTime: datetime,
          sensitiveData: JSON.stringify({
            merchantId: merchantId,
            datetime: datetime,
            orderId: txn.transaction_id,
            challenge: crypto.randomBytes(16).toString('hex'),
          }),
          signature: 'SIGNATURE_MOCK',
        };

        const res = await fetch(`${baseUrl}/check-out/initialize/${merchantId}/${txn.transaction_id}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-KM-Api-Version': 'v-0.2.0',
            'X-KM-IP-V4': '127.0.0.1',
            'X-KM-Client-Type': 'PC_WEB',
          },
          body: JSON.stringify(initPayload),
        });

        const data: any = await res.json();
        if (data.callBackUrl || data.paymentReferenceId) {
          return {
            success: true,
            paymentUrl: data.callBackUrl,
            paymentRefId: data.paymentReferenceId,
          };
        }

        return {
          success: false,
          message: data.reason || data.message || 'Nagad initialization failed.',
        };
      } catch (err: any) {
        return {
          success: false,
          message: err.message || 'Failed to reach Nagad live API endpoint.',
        };
      }
    }

    // Sandbox / Test Mode
    return {
      success: true,
      paymentUrl: `/payment-sandbox?txn=${txn.transaction_id}&gw=nagad`,
      paymentRefId: `NAGAD_REF_${txn.transaction_id}`,
    };
  }

  /**
   * Verify Payment with Nagad API
   */
  public static async verifyPayment(
    config: GatewaySecretConfig,
    paymentRefId: string
  ): Promise<{ verified: boolean; data?: any; message?: string }> {
    if (paymentRefId.startsWith('NAGAD_REF_') || config.mode === 'test') {
      return {
        verified: true,
        data: {
          paymentRefId,
          status: 'Success',
          simulated: true,
        },
      };
    }

    try {
      const baseUrl = this.getBaseUrl(config);
      const res = await fetch(`${baseUrl}/verify/payment/${paymentRefId}`, {
        method: 'GET',
        headers: {
          'X-KM-Api-Version': 'v-0.2.0',
          'X-KM-IP-V4': '127.0.0.1',
          'X-KM-Client-Type': 'PC_WEB',
        },
      });

      const data: any = await res.json();
      const verified = data.status === 'Success' && data.statusCode === '000';
      return {
        verified,
        data,
        message: data.message,
      };
    } catch (err: any) {
      return { verified: false, message: err.message };
    }
  }
}
