import axios from 'axios'

const BASE_URL = process.env.RUMAHOTP_BASE_URL || 'https://www.rumahotp.io/api'
const API_KEY = process.env.RUMAHOTP_API_KEY!

const client = axios.create({
  baseURL: BASE_URL,
  headers: {
    'x-apikey': API_KEY,
    'accept': 'application/json',
  },
  timeout: 15000,
})

// ============================================
// TYPES
// ============================================

export interface RumahOtpPricelist {
  provider_id: number
  price: number
  stock: number
  success_rate: number
}

export interface RumahOtpCountry {
  name: string
  img: string
  pricelist: RumahOtpPricelist[]
}

export interface RumahOtpOperator {
  id: number
  name: string
  img: string
}

export interface RumahOtpOrderResult {
  id: string // RO012345678
  status: string
  number: string
  price: number
  service: {
    id: number
    name: string
    img: string
  }
  country: {
    name: string
    img: string
  }
  expires_at?: string
}

export interface RumahOtpOrderStatus {
  id: string
  status: string
  number: string
  code?: string
  text?: string
  price: number
  service: { name: string; img: string }
  country: { name: string; img: string }
}

// ============================================
// GET COUNTRIES (with pricelist)
// ============================================

export async function getCountries(serviceId: number): Promise<RumahOtpCountry[]> {
  const res = await client.get('/v2/countries', {
    params: { service_id: serviceId },
  })
  return res.data?.data || res.data || []
}

// ============================================
// GET OPERATORS
// ============================================

export async function getOperators(country: string, providerId: number): Promise<RumahOtpOperator[]> {
  const res = await client.get('/v2/operators', {
    params: { country, provider_id: providerId },
  })
  return res.data?.data || res.data || []
}

// ============================================
// CREATE ORDER (Pesan Nomor)
// ============================================

export async function createOtpOrder(
  serviceId: number,
  providerId: number,
  operatorId: number
): Promise<RumahOtpOrderResult> {
  try {
    const res = await client.get('/v2/orders', {
      params: { number_id: serviceId, provider_id: providerId, operator_id: operatorId },
    })
    if (!res.data?.result && !res.data?.id) {
      throw new Error(JSON.stringify(res.data))
    }
    return res.data?.data || res.data
  } catch (error: any) {
    if (error.response?.data) {
      throw new Error(JSON.stringify(error.response.data))
    }
    throw error
  }
}

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

export async function getOtpOrderStatus(orderId: string): Promise<RumahOtpOrderStatus> {
  const res = await client.get('/v1/orders/get_status', {
    params: { order_id: orderId },
  })
  return res.data?.data || res.data
}

// ============================================
// SET ORDER STATUS
// ============================================

export type OtpOrderAction = 'cancel' | 'done' | 'resend'

export async function setOtpOrderStatus(orderId: string, status: OtpOrderAction): Promise<any> {
  const res = await client.get('/v1/orders/set_status', {
    params: { order_id: orderId, status },
  })
  return res.data
}

// ============================================
// CALCULATE SELL PRICE WITH MARKUP
// ============================================

export function applyMarkup(basePrice: number, markupPercent: number): number {
  return Math.ceil(basePrice * (1 + markupPercent / 100))
}
