import axios from 'axios'

const BASE_URL = process.env.CASHIFY_BASE_URL!
const LICENSE_KEY = process.env.CASHIFY_LICENSE_KEY!
const QRIS_ID = process.env.CASHIFY_QRIS_ID!

const cashifyClient = axios.create({
  baseURL: BASE_URL,
  headers: {
    'x-license-key': LICENSE_KEY,
    'content-type': 'application/json',
  },
  timeout: 30000,
})

// ============================================
// GENERATE QRIS PAYMENT
// ============================================

export interface GenerateQrisParams {
  amount: number
  expiredInMinutes?: number
  useUniqueCode?: boolean
  packageIds?: string[]
  qrType?: 'dynamic' | 'static'
}

export interface QrisResponse {
  transactionId: string
  qr_string: string
  originalAmount: number
  totalAmount: number
  uniqueNominal: number
  useUniqueCode: boolean
  packageIds: string[]
  status: string
  expiredAt?: string
}

export async function generateQris(params: GenerateQrisParams): Promise<QrisResponse> {
  const payload = {
    qr_id: QRIS_ID,
    amount: params.amount,
    useUniqueCode: params.useUniqueCode ?? true,
    packageIds: params.packageIds ?? ['id.dana'],
    expiredInMinutes: params.expiredInMinutes ?? 15,
    qrType: params.qrType ?? 'dynamic',
    paymentMethod: 'qris',
    useQris: true,
  }

  try {
    const res = await cashifyClient.post('/v2/qris', payload)
    if (res.data.status !== 200) throw new Error(res.data.message || 'Failed to generate QRIS')
    return res.data.data
  } catch (error: any) {
    const msg = error.response?.data?.message || error.message || 'Failed to generate QRIS'
    throw new Error(msg)
  }
}

// ============================================
// CHECK PAYMENT STATUS
// ============================================

export interface PaymentStatus {
  transactionId: string
  amount: number
  status: 'pending' | 'paid' | 'success' | 'expired' | 'cancel'
  expiredAt: string
}

export async function checkCashifyStatus(transactionId: string): Promise<PaymentStatus> {
  const res = await cashifyClient.post('/check-status', { transactionId })
  if (res.data.status !== 200) throw new Error('Failed to check payment status')
  return res.data.data
}

// ============================================
// CANCEL PAYMENT
// ============================================

export async function cancelCashifyPayment(transactionId: string) {
  const res = await cashifyClient.post('/cancel-status', { transactionId })
  return res.data
}

// ============================================
// LIST PAYMENTS
// ============================================

export interface ListPaymentsParams {
  status?: string
  page?: number
  limit?: number
  search?: string
  sort?: 'newest' | 'oldest'
}

export async function listCashifyPayments(params: ListPaymentsParams = {}) {
  const queryParams = new URLSearchParams()
  if (params.status) queryParams.set('status', params.status)
  if (params.page) queryParams.set('page', params.page.toString())
  if (params.limit) queryParams.set('limit', params.limit.toString())
  if (params.search) queryParams.set('search', params.search)
  if (params.sort) queryParams.set('sort', params.sort)

  const res = await cashifyClient.get(`/list?${queryParams.toString()}`)
  return res.data.data
}

// ============================================
// QR CODE URL GENERATOR
// ============================================

export function getQrImageUrl(data: string, size = '400x400', color = '000000', style = '2'): string {
  const encoded = encodeURIComponent(data)
  return `https://larabert-qrgen.hf.space/v1/create-qr-code?size=${size}&style=${style}&color=${color}&data=${encoded}`
}
