const API_KEY = process.env.ZAYNFLAZZ_API_KEY || ''
const BASE_URL = 'https://zaynflazz.com/api'

export interface SmmService {
  sid: string
  kategori: string
  layanan: string
  min: string
  max: string
  harga: string
  catatan: string
  average: string
  refill: string
}

export async function getZaynflazzProfile() {
  const params = new URLSearchParams()
  params.append('api_key', API_KEY)
  params.append('action', 'profile')

  const res = await fetch(`${BASE_URL}/profile`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: params.toString()
  })

  const data = await res.json()
  if (!data.status && data.data?.pesan) throw new Error(data.data.pesan)
  return data.data
}

export async function getZaynflazzServices(): Promise<SmmService[]> {
  const params = new URLSearchParams()
  params.append('api_key', API_KEY)
  params.append('action', 'layanan')

  const res = await fetch(`${BASE_URL}/sosial-media`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: params.toString()
  })

  const data = await res.json()
  // The API might return an array directly if success, or an object if failed.
  // Wait, the docs say: { "data": { "sid": "1", ... } } for success. This might be an array in reality for multiple services.
  // Actually, usually it returns { data: [ ... ] } or just the array.
  // We'll assume data.data is the array or data itself is the array if it's not wrapped.
  
  if (data.status === false && data.data?.pesan) {
    throw new Error(data.data.pesan)
  }

  // Handle case where Zaynflazz returns data wrapped in data property
  if (data.data && Array.isArray(data.data)) {
    return data.data
  } else if (Array.isArray(data)) {
    return data
  }
  
  // If it's a single object in data
  if (data.data && typeof data.data === 'object' && data.data.sid) {
    return [data.data]
  }

  return []
}

export async function placeZaynflazzOrder(serviceId: string, target: string, quantity: number, customComments?: string, customLink?: string) {
  const params = new URLSearchParams()
  params.append('api_key', API_KEY)
  params.append('action', 'pemesanan')
  params.append('layanan', serviceId)
  params.append('target', target)
  params.append('jumlah', quantity.toString())
  
  if (customComments) params.append('custom_comments', customComments)
  if (customLink) params.append('custom_link', customLink)

  const res = await fetch(`${BASE_URL}/sosial-media`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: params.toString()
  })

  const data = await res.json()
  
  // Success format: { data: { id: "1119", start_count: "200" } }
  // Error format: { status: false, data: { pesan: "Permintaan Tidak Sesuai" } }
  if (data.status === false || !data.data || !data.data.id) {
    throw new Error(data.data?.pesan || 'Order gagal di proses oleh provider')
  }

  return data.data // { id, start_count }
}

export async function checkZaynflazzOrderStatus(orderId: string) {
  const params = new URLSearchParams()
  params.append('api_key', API_KEY)
  params.append('action', 'status')
  params.append('id', orderId)

  const res = await fetch(`${BASE_URL}/sosial-media`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: params.toString()
  })

  const data = await res.json()
  
  if (data.status === false) {
    throw new Error(data.data?.pesan || 'Gagal mengecek status order')
  }

  return data.data // { id, start_count, status, remains }
}
