import { APP_CONFIG_KEYS } from '../../config/app-config-keys.js'
import { createHttpError } from '../../utils/http.js'
import { readAppConfigEntry, saveAppConfigEntry } from '../config/app-config-store.js'

/** 记忆的自定义店铺上限，超出后淘汰最早录入的。 */
const MAX_CUSTOM_SHOPS = 50

type MockCustomShopsConfig = {
  shops: string[]
}

/** 本地 Mock 用自定义店铺列表：录入过的外部平台店铺沉淀为可选项。 */
export function listAdminMockCustomShops(): string[] {
  return readAppConfigEntry({
    configKey: APP_CONFIG_KEYS.workerMockShops,
    fallback: createDefaultMockCustomShops,
    normalize: normalizeMockCustomShops,
  }).shops
}

export async function rememberAdminMockCustomShop(shopName: string): Promise<string[]> {
  const name = normalizeShopName(shopName)
  if (!name) return listAdminMockCustomShops()
  const nextShops = [name, ...listAdminMockCustomShops().filter((item) => item !== name)].slice(
    0,
    MAX_CUSTOM_SHOPS,
  )
  return saveMockCustomShops(nextShops)
}

/** 手动新增自定义店铺，重名时视为成功（幂等）。 */
export async function addAdminMockCustomShop(shopName: string): Promise<string[]> {
  const name = requireShopName(shopName, '新增')
  return saveMockCustomShops([name, ...listAdminMockCustomShops().filter((item) => item !== name)])
}

/** 重命名自定义店铺；新名称已存在时合并（移除旧名称）。 */
export async function renameAdminMockCustomShop(
  oldName: string,
  nextName: string,
): Promise<string[]> {
  const currentShops = listAdminMockCustomShops()
  const from = requireShopName(oldName, '重命名')
  const to = requireShopName(nextName, '重命名为')
  if (!currentShops.includes(from)) {
    throw createHttpError('该自定义店铺不存在', {
      statusCode: 404,
      errorCode: 'mock_custom_shop_not_found',
    })
  }
  return saveMockCustomShops(
    currentShops.flatMap((item) => {
      if (item === from) return [to]
      if (item === to) return [] // 新名称原本已存在时合并，避免重复
      return [item]
    }),
  )
}

/** 删除自定义店铺，不影响已用它生成的工单。 */
export async function deleteAdminMockCustomShop(shopName: string): Promise<string[]> {
  const currentShops = listAdminMockCustomShops()
  const name = normalizeShopName(shopName)
  if (!name || !currentShops.includes(name)) {
    throw createHttpError('该自定义店铺不存在', {
      statusCode: 404,
      errorCode: 'mock_custom_shop_not_found',
    })
  }
  return saveMockCustomShops(currentShops.filter((item) => item !== name))
}

export function normalizeMockCustomShops(rawValue: unknown): MockCustomShopsConfig {
  const shops = Array.isArray((rawValue as MockCustomShopsConfig | null)?.shops)
    ? (rawValue as MockCustomShopsConfig).shops
    : []
  const normalized = [...new Set(shops.map((item) => normalizeShopName(item)).filter(Boolean))]
  return { shops: normalized.slice(0, MAX_CUSTOM_SHOPS) }
}

async function saveMockCustomShops(shops: string[]): Promise<string[]> {
  const saved = await saveAppConfigEntry({
    configKey: APP_CONFIG_KEYS.workerMockShops,
    value: { shops },
    normalize: normalizeMockCustomShops,
  })
  return saved.shops
}

function requireShopName(value: unknown, action: string): string {
  const name = normalizeShopName(value)
  if (!name) {
    throw createHttpError(`请填写要${action}的店铺名称`, {
      statusCode: 400,
      errorCode: 'mock_custom_shop_name_required',
    })
  }
  return name
}

function createDefaultMockCustomShops(): MockCustomShopsConfig {
  return { shops: [] }
}

function normalizeShopName(value: unknown) {
  return String(value || '')
    .trim()
    .slice(0, 64)
}
