import {
  getNotificationConfig,
  getNotificationConfigFilePath,
  saveNotificationConfig,
} from '../../notification/config-service.js'
import { sendInternalNotification } from '../../notification/notification-service.js'
import {
  getScheduledJobsConfig,
  getScheduledJobsFilePath,
  saveScheduledJobsConfig,
} from '../../scheduler/config-service.js'
import {
  getScheduledJobRuntimeStates,
  reloadScheduledJobs,
  runScheduledJobNow,
} from '../../scheduler/scheduler-service.js'
import { maskSecret } from './mappers.js'

import type {
  AdminNotificationConfigInput,
  AdminNotificationTestInput,
  AdminScheduledJobsConfigInput,
} from '../../../types/admin-write-inputs.js'

type JsonObject = Record<string, any>

export function getAdminNotificationConfig() {
  const config = getNotificationConfig()

  return {
    filePath: getNotificationConfigFilePath(),
    source: mapAdminNotificationConfig(config),
  }
}

export function updateAdminNotificationConfig(payload: AdminNotificationConfigInput = {}) {
  const saved = saveNotificationConfig(payload)

  return {
    filePath: getNotificationConfigFilePath(),
    source: mapAdminNotificationConfig(saved),
  }
}

export async function testAdminNotification(payload: AdminNotificationTestInput = {}) {
  return sendInternalNotification({
    title: String(payload.title || '订单系统测试通知').trim() || '订单系统测试通知',
    body: String(payload.body || '这是一条 Bark 内部通知测试。').trim() || '这是一条 Bark 内部通知测试。',
    category: 'test',
    url: String(payload.url || '').trim(),
  })
}

export function getAdminScheduledJobsConfig() {
  const config = getScheduledJobsConfig()

  return {
    filePath: getScheduledJobsFilePath(),
    source: mapAdminScheduledJobsConfig(config),
    runtime: getScheduledJobRuntimeStates(),
  }
}

export function updateAdminScheduledJobsConfig(payload: AdminScheduledJobsConfigInput = {}) {
  const saved = saveScheduledJobsConfig(payload)
  reloadScheduledJobs()

  return {
    filePath: getScheduledJobsFilePath(),
    source: mapAdminScheduledJobsConfig(saved),
    runtime: getScheduledJobRuntimeStates(),
  }
}

export async function runAdminScheduledJobNow(jobId: unknown) {
  const result = await runScheduledJobNow(jobId)

  return {
    result,
    runtime: getScheduledJobRuntimeStates(),
  }
}

function mapAdminNotificationConfig(config: JsonObject = {}) {
  const bark = config.channels?.bark || {}

  return {
    enabled: config.enabled !== false,
    channels: {
      bark: {
        enabled: bark.enabled !== false,
        serverUrl: String(bark.serverUrl || 'https://api.day.app').trim(),
        recipients: (Array.isArray(bark.recipients) ? bark.recipients : []).map((item) => ({
          id: String(item.id || '').trim(),
          name: String(item.name || '').trim(),
          deviceKey: String(item.deviceKey || '').trim(),
          deviceKeyMasked: maskSecret(item.deviceKey),
          enabled: item.enabled !== false,
        })),
      },
    },
  }
}

function mapAdminScheduledJobsConfig(config: JsonObject = {}) {
  return {
    enabled: config.enabled !== false,
    jobs: (Array.isArray(config.jobs) ? config.jobs : []).map((item) => ({
      id: String(item.id || '').trim(),
      type: String(item.type || '').trim(),
      enabled: item.enabled === true,
      intervalSeconds: Number(item.intervalSeconds || 300),
      cooldownSeconds: Number(item.cooldownSeconds || 1800),
      config: {
        assetThreshold: Number(item.config?.assetThreshold || 500),
      },
    })),
  }
}
