import { api } from '../../../services/api'
import { TransactionLogger } from '../shared/TransactionLogger'
import { getPaymentMode } from '../lib/paymentMode'

export interface SnapTokenRequest {
  transaction_details: {
    order_id: string
    gross_amount: number
  }
  customer_details?: {
    first_name?: string
    last_name?: string
    email?: string
    phone?: string
  }
  item_details?: Array<{
    id: string
    price: number
    quantity: number
    name: string
  }>
}

export interface SnapTokenResponse {
  token: string | {
    token: string
    redirect_url: string
  }
}

export class SnapTokenService {
  static async createToken(request: SnapTokenRequest): Promise<string> {
    const mode = getPaymentMode()

    if (mode !== 'SNAP') {
      throw new Error('Snap token creation only available in SNAP mode')
    }

    try {
      TransactionLogger.logPaymentInit('SNAP', request.transaction_details.order_id, request.transaction_details.gross_amount)

      const response = await api.post<SnapTokenResponse>('/payments/snap/token', request)

      // Handle both response formats:
      // 1. Direct string: { token: "abc123" }
      // 2. Nested object: { token: { token: "abc123", redirect_url: "..." } }
      let tokenString: string
      if (typeof response.data?.token === 'string') {
        tokenString = response.data.token
      } else if (response.data?.token && typeof response.data.token === 'object') {
        tokenString = response.data.token.token
      } else {
        throw new Error('Invalid token response from server')
      }

      if (!tokenString) {
        throw new Error('Empty token received from server')
      }

      TransactionLogger.log('SNAP', 'token.created', {
        orderId: request.transaction_details.order_id,
        tokenLength: tokenString.length
      })

      return tokenString

    } catch (error) {
      TransactionLogger.logPaymentError('SNAP', request.transaction_details.order_id, error)
      throw error
    }
  }

  static validateTokenRequest(request: SnapTokenRequest): { isValid: boolean; errors: string[] } {
    const errors: string[] = []

    if (!request.transaction_details?.order_id) {
      errors.push('Order ID is required')
    }

    if (!request.transaction_details?.gross_amount || request.transaction_details.gross_amount <= 0) {
      errors.push('Valid gross amount is required')
    }

    // Validate item details sum matches gross amount
    if (request.item_details && request.item_details.length > 0) {
      const totalFromItems = request.item_details.reduce((sum, item) => {
        return sum + (item.price * item.quantity)
      }, 0)

      if (totalFromItems !== request.transaction_details.gross_amount) {
        errors.push(`Item total (${totalFromItems}) does not match gross amount (${request.transaction_details.gross_amount})`)
      }
    }

    return {
      isValid: errors.length === 0,
      errors
    }
  }
}