import { createHttpError } from '../../../utils/http.js'
import { kuaishouEticketRequest } from './http-client.js'
import { resolveKuaishouEticketConfig } from './shared.js'

type JsonObject = Record<string, any>

export async function queryKuaishouEticketStableInfo(payload: JsonObject = {}) {
  const config = resolveKuaishouEticketConfig(payload)
  const cookie = String(payload.cookie || config.cookie || '').trim()

  if (!cookie) {
    throw createHttpError('请先提供店铺 Cookie', {
      statusCode: 400,
      errorCode: 'kuaishou_eticket_missing_cookie',
    })
  }

  const response = await kuaishouEticketRequest(config.infoPath, {
    method: 'GET',
    baseUrl: config.baseUrl,
    cookie,
    timeoutMs: config.timeoutMs,
    contentType: null,
  })

  return mapKuaishouEticketStableInfoResult(response.payload, {
    baseUrl: config.baseUrl,
    cookie,
  })
}

export function mapKuaishouEticketStableInfoResult(payload: JsonObject = {}, context: JsonObject = {}) {
  const result = Number(payload?.result || 0)
  const userInfo = isPlainObject(payload?.data?.userInfo) ? payload.data.userInfo : {}
  const bizStatus = isPlainObject(payload?.data?.bizStatus) ? payload.data.bizStatus : {}

  return {
    baseUrl: String(context.baseUrl || '').trim(),
    ok: result === 1,
    result,
    errorMessage: String(payload?.error_msg || '').trim(),
    requestId: String(payload?.requestId || '').trim(),
    shop: {
      shopId: String(userInfo.userId || '').trim(),
      kshopName: String(userInfo.userName || '').trim(),
      userAvatar: String(userInfo.userAvatar || '').trim(),
      settleStatus: normalizeInteger(bizStatus.settleStatus, 0),
      hasCookie: Boolean(String(context.cookie || '').trim()),
    },
    raw: payload && typeof payload === 'object' ? payload : {},
  }
}

function normalizeInteger(value: unknown, fallback: number): number {
  const parsed = Number(value)
  return Number.isInteger(parsed) ? parsed : fallback
}

function isPlainObject(value: unknown): value is JsonObject {
  return Object.prototype.toString.call(value) === '[object Object]'
}
