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

export class RocketService {
  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://rocket.dutchbanglabank.com/api'
      : 'https://rocket-sandbox.dutchbanglabank.com/api';
  }

  public static async initPayment(
    config: GatewaySecretConfig,
    txn: ServerTransaction,
    callbackUrl: string
  ): Promise<{ success: boolean; paymentUrl?: string; orderId?: string; message?: string }> {
    if (config.mode === 'live') {
      if (!config.merchant_id || !config.app_key) {
        return {
          success: false,
          message: 'DBBL Rocket live credentials (Merchant ID, App Key) are incomplete in Admin.',
        };
      }

      try {
        const baseUrl = this.getBaseUrl(config);
        const res = await fetch(`${baseUrl}/v1/merchant/checkout`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-API-KEY': config.app_key,
          },
          body: JSON.stringify({
            merchant_id: config.merchant_id,
            terminal_id: config.terminal_id || 'TERM_01',
            invoice_no: txn.transaction_id,
            amount: txn.amount,
            currency: 'BDT',
            callback_url: callbackUrl,
          }),
        });

        const data: any = await res.json();
        if (data.status === 'SUCCESS' && data.payment_url) {
          return {
            success: true,
            paymentUrl: data.payment_url,
            orderId: data.order_id || txn.transaction_id,
          };
        }

        return {
          success: false,
          message: data.message || 'DBBL Rocket payment initialization rejected.',
        };
      } catch (err: any) {
        return {
          success: false,
          message: err.message || 'Failed to connect to DBBL Rocket gateway API.',
        };
      }
    }

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

  public static async verifyPayment(
    config: GatewaySecretConfig,
    orderId: string
  ): Promise<{ verified: boolean; data?: any; message?: string }> {
    if (orderId.startsWith('ROCKET_ORDER_') || config.mode === 'test') {
      return {
        verified: true,
        data: {
          orderId,
          status: 'SUCCESS',
          simulated: true,
        },
      };
    }

    try {
      const baseUrl = this.getBaseUrl(config);
      const res = await fetch(`${baseUrl}/v1/merchant/query/${orderId}`, {
        method: 'GET',
        headers: {
          'X-API-KEY': config.app_key || '',
        },
      });

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