/**
 * KudaBankService
 * Handles Kuda Bank virtual account payments
 * Features: Instant virtual account generation, automated verification
 */

const axios = require('axios');
const PaymentServiceInterface = require('./PaymentServiceInterface');

class KudaBankService extends PaymentServiceInterface {
  constructor() {
    super();
    this.apiUrl = process.env.KUDA_API_URL || 'https://kuda-openapi.kuda.com/v2.1';
    this.email = process.env.KUDA_EMAIL;
    this.apiKey = process.env.KUDA_API_KEY;
    this.token = null;
    this.tokenExpiry = null;
  }

  /**
   * Get or refresh authentication token
   */
  async getToken() {
    // Return cached token if still valid
    if (this.token && this.tokenExpiry && Date.now() < this.tokenExpiry) {
      return this.token;
    }

    try {
      const response = await axios.post(`${this.apiUrl}/Account/GetToken`, {
        email: this.email,
        apiKey: this.apiKey
      });

      if (response.data && response.data.data && response.data.data.token) {
        this.token = response.data.data.token;
        // Token valid for 1 hour
        this.tokenExpiry = Date.now() + (55 * 60 * 1000); // 55 minutes
        return this.token;
      }

      throw new Error('Failed to get Kuda token');
    } catch (error) {
      console.error('Kuda token error:', error.message);
      throw new Error(`Kuda authentication failed: ${error.message}`);
    }
  }

  /**
   * Create virtual account for user
   */
  async createVirtualAccount(customerName, customerEmail, trackingReference) {
    try {
      const token = await this.getToken();

      const response = await axios.post(
        `${this.apiUrl}/Account/CreateVirtualAccount`,
        {
          email: customerEmail || '',
          phoneNumber: '',
          lastName: customerName || 'WakaTraffic User',
          firstName: '',
          trackingReference: trackingReference
        },
        {
          headers: {
            Authorization: `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        }
      );

      if (response.data && response.data.data) {
        const data = response.data.data;

        return {
          success: true,
          data: {
            account_number: data.accountNumber,
            account_name: data.accountName,
            bank_name: 'Kuda Bank',
            bank_code: '090267',
            reference: trackingReference
          },
          message: 'Virtual account created successfully'
        };
      }

      return {
        success: false,
        message: 'Failed to create virtual account'
      };
    } catch (error) {
      console.error('Kuda virtual account error:', error.message);
      return {
        success: false,
        message: `Failed to create virtual account: ${error.message}`
      };
    }
  }

  /**
   * Initialize payment - Creates virtual account
   */
  async initializePayment(amount, reference, metadata = {}) {
    return await this.createVirtualAccount(
      metadata.customer_name || metadata.username || 'WakaTraffic User',
      metadata.customer_email || metadata.email || '',
      reference
    );
  }

  /**
   * Verify payment by checking transaction history
   */
  async verifyPayment(reference) {
    try {
      const token = await this.getToken();

      const response = await axios.post(
        `${this.apiUrl}/Account/GetVirtualAccountBalance`,
        { trackingReference: reference },
        {
          headers: {
            Authorization: `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        }
      );

      if (response.data && response.data.data) {
        const data = response.data.data;

        return {
          success: true,
          data: {
            status: 'completed',
            amount: parseFloat(data.ledgerBalance || 0),
            reference: reference,
            account_number: data.accountNumber
          },
          message: 'Payment verified successfully'
        };
      }

      return {
        success: false,
        message: 'Payment not found or not completed'
      };
    } catch (error) {
      console.error('Kuda verify error:', error.message);
      return {
        success: false,
        message: `Verification failed: ${error.message}`
      };
    }
  }

  /**
   * Get payment status
   */
  async getPaymentStatus(reference) {
    const verification = await this.verifyPayment(reference);
    return verification.success ? 'completed' : 'pending';
  }

  /**
   * Handle webhook from Kuda
   */
  async handleWebhook(payload, headers = {}) {
    try {
      // Kuda sends notifications for account credits
      if (payload.data && payload.data.accountNumber) {
        return {
          success: true,
          data: {
            reference: payload.data.trackingReference,
            amount: parseFloat(payload.data.amount || 0),
            status: 'completed',
            transaction_id: payload.data.transactionReference,
            account_number: payload.data.accountNumber
          }
        };
      }

      return { success: false, message: 'Invalid webhook payload' };
    } catch (error) {
      console.error('Kuda webhook error:', error.message);
      return { success: false, message: error.message };
    }
  }

  /**
   * Verify webhook signature
   */
  verifyWebhookSignature(payload, signature) {
    const crypto = require('crypto');
    const computedSignature = crypto
      .createHmac('sha256', this.apiKey)
      .update(payload)
      .digest('hex');

    return crypto.timingSafeEqual(
      Buffer.from(computedSignature),
      Buffer.from(signature)
    );
  }

  /**
   * Get service configuration
   */
  getConfig() {
    return {
      name: 'Kuda Bank',
      code: 'kuda',
      type: 'virtual_account',
      isAutomated: true,
      requiresProof: false,
      processingTime: 0 // Instant
    };
  }
}

module.exports = KudaBankService;
