/**
 * USSDPaymentService
 * Handles USSD-based bank payments
 * Features: USSD codes display, manual verification
 */

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

class USSDPaymentService extends PaymentServiceInterface {
  constructor(pool) {
    super();
    this.pool = pool; // Database connection pool
    this.ussdCodes = [
      {
        bank_name: 'Access Bank',
        ussd_code: '*901#',
        account_number: '0123456789',
        account_name: 'WakaTraffic Limited',
        steps: [
          'Dial *901#',
          'Select Transfer',
          'Select To Access Account',
          'Enter Account Number: 0123456789',
          'Enter Amount',
          'Enter PIN to confirm'
        ]
      },
      {
        bank_name: 'GTBank',
        ussd_code: '*737#',
        account_number: '0987654321',
        account_name: 'WakaTraffic Limited',
        steps: [
          'Dial *737#',
          'Select Transfer',
          'Select To GTB Account',
          'Enter Account Number: 0987654321',
          'Enter Amount',
          'Enter PIN to confirm'
        ]
      },
      {
        bank_name: 'First Bank',
        ussd_code: '*894#',
        account_number: '1234567890',
        account_name: 'WakaTraffic Limited',
        steps: [
          'Dial *894#',
          'Select Transfer',
          'Select To First Bank Account',
          'Enter Account Number: 1234567890',
          'Enter Amount',
          'Enter PIN to confirm'
        ]
      },
      {
        bank_name: 'Zenith Bank',
        ussd_code: '*966#',
        account_number: '2234567890',
        account_name: 'WakaTraffic Limited',
        steps: [
          'Dial *966#',
          'Select Transfer',
          'Enter Account Number: 2234567890',
          'Enter Amount',
          'Enter PIN to confirm'
        ]
      },
      {
        bank_name: 'UBA',
        ussd_code: '*919#',
        account_number: '3234567890',
        account_name: 'WakaTraffic Limited',
        steps: [
          'Dial *919#',
          'Select Transfer',
          'Select To UBA Account',
          'Enter Account Number: 3234567890',
          'Enter Amount',
          'Enter PIN to confirm'
        ]
      }
    ];
  }

  /**
   * Initialize payment - Return USSD codes and instructions
   */
  async initializePayment(amount, reference, metadata = {}) {
    try {
      return {
        success: true,
        data: {
          ussd_options: this.ussdCodes,
          amount: amount,
          reference: reference,
          instructions: [
            'Select your bank from the list above',
            'Dial the USSD code from your registered phone number',
            'Follow the steps to transfer the exact amount',
            `Transfer exactly ₦${amount.toLocaleString()} to the account number shown`,
            'No internet required - works on all phones!',
            'Your account will be credited automatically within 10 minutes'
          ],
          important_notes: [
            'You must transfer from a phone number registered with your bank',
            'Transfer the EXACT amount shown',
            'Keep your transaction SMS as proof',
            'Do not share your PIN with anyone'
          ],
          expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString() // 24 hours
        },
        message: 'USSD payment codes generated successfully'
      };
    } catch (error) {
      console.error('USSD init error:', error.message);
      return {
        success: false,
        message: `Initialization failed: ${error.message}`
      };
    }
  }

  /**
   * Verify payment - Check database for payment status
   */
  async verifyPayment(reference) {
    try {
      if (!this.pool) {
        return {
          success: false,
          message: 'Database connection not available'
        };
      }

      const [deposits] = await this.pool.execute(
        `SELECT status, amount, payment_account, verified_at, transaction_id
         FROM deposits
         WHERE reference = ?`,
        [reference]
      );

      if (deposits.length === 0) {
        return {
          success: false,
          message: 'Deposit not found'
        };
      }

      const deposit = deposits[0];

      if (deposit.status === 'completed' && deposit.verified_at) {
        return {
          success: true,
          data: {
            status: 'completed',
            amount: parseFloat(deposit.amount),
            reference: reference,
            payment_account: deposit.payment_account,
            transaction_id: deposit.transaction_id,
            verified_at: deposit.verified_at
          },
          message: 'Payment verified and completed'
        };
      } else if (deposit.status === 'processing') {
        return {
          success: false,
          data: {
            status: 'processing',
            reference: reference
          },
          message: 'Payment detected, processing...'
        };
      } else {
        return {
          success: false,
          data: {
            status: 'pending',
            reference: reference
          },
          message: 'Awaiting USSD payment. Please complete the transfer.'
        };
      }
    } catch (error) {
      console.error('USSD verify error:', error.message);
      return {
        success: false,
        message: `Verification failed: ${error.message}`
      };
    }
  }

  /**
   * Record USSD payment details (when user confirms transfer)
   */
  async recordPayment(reference, metadata = {}) {
    try {
      if (!this.pool) {
        throw new Error('Database connection not available');
      }

      const [result] = await this.pool.execute(
        `UPDATE deposits
         SET status = 'processing',
             payment_account = ?,
             transaction_id = ?,
             user_note = ?,
             updated_at = NOW()
         WHERE reference = ?`,
        [
          metadata.bank_name || null,
          metadata.transaction_id || null,
          metadata.user_note || 'USSD Payment completed',
          reference
        ]
      );

      if (result.affectedRows > 0) {
        return {
          success: true,
          message: 'Payment details recorded. Verification in progress.'
        };
      }

      return {
        success: false,
        message: 'Failed to record payment details'
      };
    } catch (error) {
      console.error('Record payment error:', error.message);
      return {
        success: false,
        message: `Record failed: ${error.message}`
      };
    }
  }

  /**
   * Get payment status
   */
  async getPaymentStatus(reference) {
    const verification = await this.verifyPayment(reference);

    if (verification.success) {
      return 'completed';
    } else if (verification.data && verification.data.status) {
      return verification.data.status;
    }

    return 'pending';
  }

  /**
   * Handle webhook - Not applicable for USSD
   */
  async handleWebhook(payload, headers = {}) {
    return {
      success: false,
      message: 'Webhooks not supported for USSD payments'
    };
  }

  /**
   * Verify webhook signature - Not applicable
   */
  verifyWebhookSignature(payload, signature) {
    return false;
  }

  /**
   * Get service configuration
   */
  getConfig() {
    return {
      name: 'USSD Payment',
      code: 'ussd',
      type: 'ussd',
      isAutomated: false, // Semi-automated (auto-detected via Mono)
      requiresProof: false,
      processingTime: 10 // 10 minutes average
    };
  }
}

module.exports = USSDPaymentService;
