import { APP_CONFIG_KEYS } from '../../config/app-config-keys.js'
import type { JsonObject } from '../../types/json.js'
import { readAppConfigEntry, saveAppConfigEntry } from '../config/app-config-store.js'

export type WorkerHallConfig = {
  maxVisibleOrders: number
  categoryMaxVisibleOrders: Record<string, number>
}

export function getWorkerHallConfig(): WorkerHallConfig {
  return readAppConfigEntry({
    configKey: APP_CONFIG_KEYS.workerHall,
    fallback: createDefaultWorkerHallConfig,
    normalize: normalizeWorkerHallConfig,
  })
}

export async function saveWorkerHallConfig(rawValue: unknown): Promise<WorkerHallConfig> {
  return saveAppConfigEntry({
    configKey: APP_CONFIG_KEYS.workerHall,
    value: rawValue,
    normalize: normalizeWorkerHallConfig,
  })
}

export function createDefaultWorkerHallConfig(): WorkerHallConfig {
  return { maxVisibleOrders: 50, categoryMaxVisibleOrders: {} }
}

export function normalizeWorkerHallConfig(rawValue: unknown): WorkerHallConfig {
  const source = isPlainObject(rawValue) ? rawValue : {}
  const value = Number(source.maxVisibleOrders ?? source.max_visible_orders)
  return {
    maxVisibleOrders: Number.isInteger(value) ? Math.min(500, Math.max(1, value)) : 50,
    categoryMaxVisibleOrders: normalizeCategoryMaxVisibleOrders(
      source.categoryMaxVisibleOrders ?? source.category_max_visible_orders,
    ),
  }
}

function normalizeCategoryMaxVisibleOrders(value: unknown): Record<string, number> {
  if (!isPlainObject(value)) return {}
  return Object.entries(value).reduce<Record<string, number>>((result, [categoryId, raw]) => {
    const id = Number(categoryId)
    const limit = Number(raw)
    if (Number.isInteger(id) && id > 0 && Number.isInteger(limit) && limit >= 1 && limit <= 500) {
      result[String(id)] = limit
    }
    return result
  }, {})
}

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