import {
  consumeKuaishouEticket,
  queryKuaishouEticketConsumeDetail,
} from '../../platforms/kuaishou-eticket/consume-service.js'
import {
  findKuaishouEticketShopConfig,
  getFirstAvailableKuaishouEticketShop,
  getKuaishouEticketSourceConfig,
  getKuaishouEticketSourceFilePath,
  listKuaishouEticketShopConfigs,
  saveKuaishouEticketSourceConfig,
} from '../../platforms/kuaishou-eticket/source-config-service.js'
import { queryKuaishouEticketStableInfo } from '../../platforms/kuaishou-eticket/info-service.js'
import { resolveKuaishouEticketAdminContext } from './context.js'
import { mapAdminKuaishouEticketSourceConfig } from './mappers.js'

type JsonObject = Record<string, any>

function resolveAdminKuaishouEticketContext(payload: JsonObject = {}) {
  return resolveKuaishouEticketAdminContext(payload, {
    savedSource: getKuaishouEticketSourceConfig(),
    findShopConfig: findKuaishouEticketShopConfig,
    getFirstAvailableShop: getFirstAvailableKuaishouEticketShop,
  })
}

export function getAdminKuaishouEticketSourceConfig() {
  const config = getKuaishouEticketSourceConfig()

  return {
    filePath: getKuaishouEticketSourceFilePath(),
    source: mapAdminKuaishouEticketSourceConfig(config, listKuaishouEticketShopConfigs(config)),
  }
}

export function updateAdminKuaishouEticketSourceConfig(payload: JsonObject = {}) {
  const saved = saveKuaishouEticketSourceConfig({
    enabled: payload.enabled !== false,
    baseUrl: String(payload.baseUrl || '').trim() || 'https://s.kwaixiaodian.com',
    shops: Array.isArray(payload.shops) ? payload.shops : [],
  })

  return {
    filePath: getKuaishouEticketSourceFilePath(),
    source: mapAdminKuaishouEticketSourceConfig(saved, listKuaishouEticketShopConfigs(saved)),
  }
}

export async function queryAdminKuaishouEticketDetail(payload: JsonObject = {}) {
  const context = resolveAdminKuaishouEticketContext(payload)

  return queryKuaishouEticketConsumeDetail({
    baseUrl: context.baseUrl,
    cookie: context.cookie,
    eTicketId: String(payload.eTicketId || '').trim(),
  })
}

export async function queryAdminKuaishouEticketShopInfo(payload: JsonObject = {}) {
  const context = resolveAdminKuaishouEticketContext(payload)

  return queryKuaishouEticketStableInfo({
    baseUrl: context.baseUrl,
    cookie: context.cookie,
  })
}

export async function consumeAdminKuaishouEticket(payload: JsonObject = {}) {
  const context = resolveAdminKuaishouEticketContext(payload)

  return consumeKuaishouEticket({
    baseUrl: context.baseUrl,
    cookie: context.cookie,
    eTicketId: String(payload.eTicketId || '').trim(),
    oid: String(payload.oid || '').trim(),
    formToken: String(payload.formToken || '').trim(),
    num: payload.num,
    storeId: String(payload.storeId || '').trim(),
  })
}
