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 WorkerAnnouncementConfig = {
  enabled: boolean
  content: string
}

export function getWorkerAnnouncementConfig(): WorkerAnnouncementConfig {
  return readAppConfigEntry({
    configKey: APP_CONFIG_KEYS.workerAnnouncement,
    fallback: createDefaultWorkerAnnouncementConfig,
    normalize: normalizeWorkerAnnouncementConfig,
  })
}

export async function saveWorkerAnnouncementConfig(
  rawValue: unknown,
): Promise<WorkerAnnouncementConfig> {
  return saveAppConfigEntry({
    configKey: APP_CONFIG_KEYS.workerAnnouncement,
    value: rawValue,
    normalize: normalizeWorkerAnnouncementConfig,
  })
}

export function createDefaultWorkerAnnouncementConfig(): WorkerAnnouncementConfig {
  return {
    enabled: true,
    content: '平台担保交易，拒绝私下转账/共享验证码，交接全程留痕。',
  }
}

export function normalizeWorkerAnnouncementConfig(rawValue: unknown): WorkerAnnouncementConfig {
  const source = isPlainObject(rawValue) ? rawValue : {}
  return {
    enabled: source.enabled !== false,
    content: String(source.content || '')
      .trim()
      .slice(0, 300),
  }
}

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