import axios from 'axios'
import crypto from 'crypto'
import http from 'http'
import https from 'https'

const httpAgent = new http.Agent({ family: 4 })
const httpsAgent = new https.Agent({ family: 4 })

const BASE_URL = process.env.VIP_API_URL!
const API_KEY = process.env.VIP_API_KEY!
const API_ID = process.env.VIP_API_ID!

// Generate MD5 signature: md5(API ID + API KEY)
function getSign(): string {
  return crypto.createHash('md5').update(API_ID + API_KEY).digest('hex')
}

interface VipBaseParams {
  key: string
  sign: string
  type: string
  [key: string]: string | number | undefined
}

async function vipPost(params: Record<string, string | number | undefined>) {
  const payload = new URLSearchParams()
  payload.append('key', API_KEY)
  payload.append('sign', getSign())
  
  for (const [k, v] of Object.entries(params)) {
    if (v !== undefined) {
      payload.append(k, String(v))
    }
  }

  const response = await axios.post(BASE_URL, payload.toString(), {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    timeout: 30000,
    httpAgent,
    httpsAgent,
  })

  return response.data
}

// ============================================
// GET SERVICES (Product List)
// ============================================

export interface VipProduct {
  code: string
  game: string
  name: string
  price: {
    basic: number
    premium: number
    special: number
  }
  description: string
  server: string
  status: 'available' | 'empty'
}

export async function getVipServices(filterGame?: string, filterStatus?: string): Promise<VipProduct[]> {
  const params: Record<string, string> = { type: 'services' }
  if (filterGame) params.filter_game = filterGame
  if (filterStatus) params.filter_status = filterStatus

  const res = await vipPost(params)
  if (!res.result) throw new Error(res.message || 'Failed to fetch VIP services')
  return res.data
}

// ============================================
// GET STOCK
// ============================================

export async function getVipStock(serviceCode: string) {
  const res = await vipPost({ type: 'service-stock', service: serviceCode })
  if (!res.result) throw new Error(res.message || 'Failed to get stock')
  return res.data
}

// ============================================
// GET NICKNAME (Validate game ID)
// ============================================

export async function getVipNickname(code: string, target: string, additionalTarget?: string) {
  const params: Record<string, string> = { type: 'get-nickname', code, target }
  if (additionalTarget) params.additional_target = additionalTarget

  const res = await vipPost(params)
  if (!res.result) throw new Error(res.message || 'Invalid game ID')
  return { nickname: res.data as string, country: res.country }
}

// ============================================
// CREATE ORDER
// ============================================

export interface VipOrderParams {
  service: string
  dataNo: string
  dataZone?: string
  additionalData?: string
}

export interface VipOrderResult {
  trxid: string
  data: string
  zone: string
  service: string
  status: string
  note: string
  balance: number
  price: number
}

export async function createVipOrder(params: VipOrderParams): Promise<VipOrderResult> {
  const payload: Record<string, string> = {
    type: 'order',
    service: params.service,
    data_no: params.dataNo,
  }

  if (params.dataZone) payload.data_zone = params.dataZone
  if (params.additionalData) payload.additional_data = params.additionalData

  const res = await vipPost(payload)
  if (!res.result) throw new Error(res.message || 'Failed to create VIP order')
  return res.data
}

// ============================================
// CHECK ORDER STATUS
// ============================================

export interface VipOrderStatus {
  trxid: string
  data: string
  zone: string
  service: string
  status: 'waiting' | 'processing' | 'success' | 'error'
  note: string
  price: number
}

export async function checkVipOrderStatus(trxid: string): Promise<VipOrderStatus> {
  const res = await vipPost({ type: 'status', trxid })
  if (!res.result) throw new Error(res.message || 'Failed to check order status')
  return Array.isArray(res.data) ? res.data[0] : res.data
}

export async function checkMultipleVipOrders(limit: number = 10): Promise<VipOrderStatus[]> {
  const res = await vipPost({ type: 'status', limit: limit.toString() })
  if (!res.result) throw new Error(res.message || 'Failed to fetch orders')
  return res.data
}

// ============================================
// WEBHOOK SIGNATURE VERIFICATION
// ============================================

export function verifyVipWebhook(signature: string): boolean {
  const expected = getSign()
  return signature === expected
}
