import { readBody } from 'h3';
import db from '~/utils/sqlite';
import { useResponseError, useResponseSuccess } from '~/utils/response';
import { testTelegramConfig } from '~/utils/telegram-bot';

export default defineEventHandler(async (event) => {
  const body = await readBody(event);

  if (!body?.name || !body?.botToken || !body?.chatId) {
    return useResponseError('缺少必填字段', -1);
  }

  const notificationTypes = Array.isArray(body.notificationTypes)
    ? body.notificationTypes
    : ['transaction'];

  // 测试配置是否有效
  const testResult = await testTelegramConfig(body.botToken, body.chatId);
  if (!testResult.success) {
    return useResponseError(
      `Telegram配置测试失败: ${testResult.error}`,
      -1,
    );
  }

  const now = new Date().toISOString();

  const result = db
    .prepare<unknown, [string, string, string, string, number, string, string]>(
      `
      INSERT INTO telegram_notification_configs (name, bot_token, chat_id, notification_types, is_enabled, created_at, updated_at)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `,
    )
    .run(
      body.name,
      body.botToken,
      body.chatId,
      JSON.stringify(notificationTypes),
      body.isEnabled !== false ? 1 : 0,
      now,
      now,
    );

  return useResponseSuccess({
    id: result.lastInsertRowid,
    name: body.name,
    botToken: body.botToken,
    chatId: body.chatId,
    notificationTypes,
    isEnabled: body.isEnabled !== false,
    createdAt: now,
    updatedAt: now,
  });
});
