import { affiliateDashRequest } from './http-client.js'

export type AffiliateDashProduct = ReturnType<typeof mapAffiliateDashProduct>
export type AffiliateDashProductListResult = ReturnType<typeof mapAffiliateDashProductList>

export async function listAffiliateDashProducts(
  input: {
    page?: number | undefined
    size?: number | undefined
  } = {},
) {
  const params = new URLSearchParams()
  if (input.page !== undefined) {
    params.set('page', String(input.page))
  }
  if (input.size !== undefined) {
    params.set('size', String(input.size))
  }
  const query = params.toString()
  const json = await affiliateDashRequest({
    method: 'GET',
    pathname: `/api/client/v1/products${query ? `?${query}` : ''}`,
  })
  return mapAffiliateDashProductList(json.data)
}

/** 翻页拉取全部可售商品（默认每页 100）。 */
export async function listAllAffiliateDashProducts(
  input: {
    pageSize?: number | undefined
  } = {},
) {
  const size = Math.max(1, Number(input.pageSize || 100) || 100)
  const products: AffiliateDashProduct[] = []
  let page = 1
  let total = Infinity

  while (products.length < total) {
    const result = await listAffiliateDashProducts({ page, size })
    products.push(...result.list)
    total = result.total
    if (result.list.length === 0) {
      break
    }
    page += 1
  }

  return { list: products, total: products.length }
}

export function mapAffiliateDashProductList(value: unknown) {
  const source = asRecord(value)
  const list = Array.isArray(source.list) ? source.list : []
  return {
    list: list.map(mapAffiliateDashProduct),
    total: Number(source.total || list.length || 0) || 0,
    page: Number(source.page || 1) || 1,
    size: Number(source.size || list.length || 0) || 0,
  }
}

export function mapAffiliateDashProduct(value: unknown) {
  const source = asRecord(value)
  const product = asRecord(source.product)

  return {
    sku: String(source.sku || product.code || '').trim(),
    displayName: String(source.display_name || product.name || '').trim(),
    priceAmount: Number(source.price_amount ?? 0) || 0,
    costAmount: Number(source.cost_amount ?? 0) || 0,
    currency: String(source.currency || '').trim(),
    stock: Number.isInteger(Number(source.stock)) ? Number(source.stock) : -1,
    status: String(source.status || product.status || '').trim(),
    category: String(product.category || '').trim(),
    code: String(product.code || '').trim(),
    productId: Number(source.product_id || product.id || 0) || 0,
  }
}

function asRecord(value: unknown): Record<string, unknown> {
  return Object.prototype.toString.call(value) === '[object Object]'
    ? (value as Record<string, unknown>)
    : {}
}
