import { Router } from 'express'

import {
  getAdminNotificationConfig,
  getAdminScheduledJobsConfig,
  runAdminScheduledJobNow,
  testAdminNotification,
  updateAdminNotificationConfig,
  updateAdminScheduledJobsConfig,
} from '../../../services/admin/platform-config/notification-service.js'
import type {
  AdminEntityRouteParams,
  AdminNotificationConfigRouteBody,
  AdminNotificationTestRouteBody,
  AdminScheduledJobsConfigRouteBody,
} from '../../../types/admin/route-inputs.js'
import { createJsonHandler } from '../session.js'
import type { JsonRecord } from '../../../types/json.js'

const router = Router()

router.get(
  '/notifications',
  createJsonHandler(() => getAdminNotificationConfig(), {
    successMessage: 'ok',
    errorMessage: '读取内部通知配置失败',
    scope: '[admin/platform-config/notifications]',
  }),
)

router.post(
  '/notifications',
  createJsonHandler(
    (req) => updateAdminNotificationConfig(req.body as AdminNotificationConfigRouteBody),
    {
      successMessage: '内部通知配置已保存',
      errorMessage: '保存内部通知配置失败',
      scope: '[admin/platform-config/notifications]',
      audit: (_req, data) => {
        const result = data as JsonRecord
        return {
          action: 'platform_notification_config_updated',
          targetType: 'platform_config',
          targetId: 'notifications',
          data: {
            filePath: String(result.filePath || '').trim(),
            enabled: Boolean(result.source?.enabled),
            barkRecipientCount: Array.isArray(result.source?.channels?.bark?.recipients)
              ? result.source.channels.bark.recipients.length
              : 0,
            wpushRecipientCount: Array.isArray(result.source?.channels?.wpush?.recipients)
              ? result.source.channels.wpush.recipients.length
              : 0,
          },
        }
      },
    },
  ),
)

router.post(
  '/notifications/test',
  createJsonHandler((req) => testAdminNotification(req.body as AdminNotificationTestRouteBody), {
    successMessage: '内部通知测试已执行',
    errorMessage: '内部通知测试失败',
    scope: '[admin/platform-config/notifications/test]',
    audit: (_req, data) => {
      const result = data as JsonRecord
      return {
        action: 'platform_notification_test_sent',
        targetType: 'platform_config',
        targetId: 'notifications',
        data: {
          channel: String(result.channel || '').trim(),
          successCount: Number(result.successCount || 0),
          failedCount: Number(result.failedCount || 0),
        },
      }
    },
  }),
)

router.get(
  '/scheduled-jobs',
  createJsonHandler(() => getAdminScheduledJobsConfig(), {
    successMessage: 'ok',
    errorMessage: '读取定时任务配置失败',
    scope: '[admin/platform-config/scheduled-jobs]',
  }),
)

router.post(
  '/scheduled-jobs',
  createJsonHandler(
    (req) => updateAdminScheduledJobsConfig(req.body as AdminScheduledJobsConfigRouteBody),
    {
      successMessage: '定时任务配置已保存',
      errorMessage: '保存定时任务配置失败',
      scope: '[admin/platform-config/scheduled-jobs]',
      audit: (_req, data) => {
        const result = data as JsonRecord
        return {
          action: 'platform_scheduled_jobs_updated',
          targetType: 'platform_config',
          targetId: 'scheduled_jobs',
          data: {
            filePath: String(result.filePath || '').trim(),
            enabled: Boolean(result.source?.enabled),
            jobCount: Array.isArray(result.source?.jobs) ? result.source.jobs.length : 0,
          },
        }
      },
    },
  ),
)

router.post(
  '/scheduled-jobs/:id/run',
  createJsonHandler((req) => runAdminScheduledJobNow((req.params as AdminEntityRouteParams).id), {
    successMessage: '定时任务已执行',
    errorMessage: '执行定时任务失败',
    scope: '[admin/platform-config/scheduled-jobs/:id/run]',
    audit: (req, data) => {
      const result = data as JsonRecord
      return {
        action: 'platform_scheduled_job_run',
        targetType: 'platform_config',
        targetId: String((req.params as AdminEntityRouteParams).id || '').trim(),
        data: {
          status: String(result.result?.status || '').trim(),
          message: String(result.result?.message || '').trim(),
        },
      }
    },
  }),
)

export default router
