import { getKuaishouFeifeiConfig } from './config.js'
import { kuaishouFeifeiRequest } from './http-client.js'
import type { JsonObject } from '../../../types/json.js'

export type KuaishouFeifeiProductListResult = ReturnType<typeof mapKuaishouFeifeiProductList>

export async function listKuaishouFeifeiProducts(
  input: {
    page?: number
    perPage?: number
    status?: string
    supplyProductName?: string
  } = {},
) {
  const page = Math.max(1, Number(input.page || 1) || 1)
  const perPage = Math.min(100, Math.max(1, Number(input.perPage || 20) || 20))
  const filters: JsonObject = {}
  const status = String(input.status || 'on_sale').trim()
  const supplyProductName = String(input.supplyProductName || '').trim()

  if (status) filters.status = status
  if (supplyProductName) filters.supply_product_name = supplyProductName

  const response = await kuaishouFeifeiRequest('/api/open/v1/products/index', {
    page,
    per_page: perPage,
    filters,
  })

  return mapKuaishouFeifeiProductList(response.data)
}

export async function createKuaishouFeifeiOrder(input: {
  platformOrderNo: string
  productCode: string
  platformBuyNum?: number
  platformAmount?: number
  playerAccount?: string
  playerGameRegion?: string
  playerGameSrv?: string
  playerGameRole?: string
  submitPlayer?: boolean
  notifyUrl?: string
}) {
  const config = getKuaishouFeifeiConfig()
  const payload: JsonObject = {
    platform_order_no: input.platformOrderNo,
    product_code: input.productCode,
    platform_buy_num: Math.max(1, Number(input.platformBuyNum || 1) || 1),
  }

  if (input.platformAmount != null) payload.platform_amount = input.platformAmount
  if (input.playerAccount) payload.player_account = input.playerAccount
  if (input.playerGameRegion) payload.player_game_region = input.playerGameRegion
  if (input.playerGameSrv) payload.player_game_srv = input.playerGameSrv
  if (input.playerGameRole) payload.player_game_role = input.playerGameRole
  if (input.submitPlayer === true) payload.submit_player = true
  if (input.notifyUrl || config.notifyUrl) payload.notify_url = input.notifyUrl || config.notifyUrl

  const response = await kuaishouFeifeiRequest('/api/open/v1/orders/store', payload)
  return mapKuaishouFeifeiOrder(response.data?.order)
}

export async function queryKuaishouFeifeiOrder(input: {
  platformOrderNo?: string
  orderNo?: string
}) {
  const payload: JsonObject = {}
  if (input.platformOrderNo) payload.platform_order_no = input.platformOrderNo
  if (input.orderNo) payload.order_no = input.orderNo

  const response = await kuaishouFeifeiRequest('/api/open/v1/orders/show', payload)
  return mapKuaishouFeifeiOrder(response.data?.order)
}

export function mapKuaishouFeifeiOrder(value: unknown) {
  const source =
    value && typeof value === 'object' && !Array.isArray(value) ? (value as JsonObject) : {}
  const h5 = source.h5 && typeof source.h5 === 'object' ? (source.h5 as JsonObject) : {}

  return {
    orderNo: String(source.order_no || '').trim(),
    platformOrderNo: String(source.platform_order_no || '').trim(),
    productCode: String(source.product_code || '').trim(),
    productName: String(source.product_name || '').trim(),
    rechargeStatus: Number(source.recharge_status ?? source.status ?? 0) || 0,
    rechargeStatusLabel: String(source.recharge_status_label || source.status_label || '').trim(),
    pointsCharged: Number(source.points_charged || 0) || 0,
    playerAccount: String(source.player_account || '').trim(),
    platformBuyNum: Number(source.platform_buy_num || 1) || 1,
    rechargeResultMessage: String(source.recharge_result_message || '').trim(),
    createdAt: String(source.created_at || '').trim(),
    updatedAt: String(source.updated_at || '').trim(),
    rechargeFinishAt: String(source.recharge_finish_at || '').trim(),
    h5: {
      entryUrl: String(h5.entry_url || '').trim(),
      rechargeUrl: String(h5.recharge_url || '').trim(),
    },
    raw: source,
  }
}

export function mapKuaishouFeifeiProductList(value: unknown) {
  const source =
    value && typeof value === 'object' && !Array.isArray(value) ? (value as JsonObject) : {}
  const list = Array.isArray(source.list) ? source.list : []

  return {
    items: list.map((item) => mapKuaishouFeifeiProduct(item)),
    total: Number(source.total || list.length) || 0,
    page: Number(source.page || 1) || 1,
    perPage: Number(source.per_page || source.perPage || list.length || 20) || 20,
    raw: source,
  }
}

export function mapKuaishouFeifeiProduct(value: unknown) {
  const source =
    value && typeof value === 'object' && !Array.isArray(value) ? (value as JsonObject) : {}

  return {
    productCode: String(source.product_code || '').trim(),
    name: String(source.name || '').trim(),
    channel: String(source.channel || '').trim(),
    externalProductId: String(source.external_product_id || '').trim(),
    imageUrl: String(source.image_url || '').trim(),
    status: String(source.status || '').trim(),
    supplyStatus: String(source.supply_status || '').trim(),
    supplyPricePoints: Number(source.supply_price_points || 0) || 0,
    feePoints: Number(source.fee_points || 0) || 0,
    unitCostPoints: Number(source.unit_cost_points || 0) || 0,
    maxOrderQuantity: Number(source.max_order_quantity || 0) || 0,
    salePricePoints:
      source.sale_price_points == null ? null : Number(source.sale_price_points || 0) || 0,
    raw: source,
  }
}
