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 id = event.context.params?.id;
  if (!id) {
    return useResponseError('缺少ID参数', -1);
  }

  const body = await readBody(event);

  // 如果更新了botToken或chatId，需要测试配置
  if (body.botToken || body.chatId) {
    const existing = db
      .prepare<{ bot_token: string; chat_id: string }>('SELECT bot_token, chat_id FROM telegram_notification_configs WHERE id = ?')
      .get(id);

    if (!existing) {
      return useResponseError('配置不存在', -1);
    }

    const tokenToTest = body.botToken || existing.bot_token;
    const chatIdToTest = body.chatId || existing.chat_id;

    const testResult = await testTelegramConfig(tokenToTest, chatIdToTest);
    if (!testResult.success) {
      return useResponseError(
        `Telegram配置测试失败: ${testResult.error}`,
        -1,
      );
    }
  }

  const updates: string[] = [];
  const values: (string | number)[] = [];

  if (body.name !== undefined) {
    updates.push('name = ?');
    values.push(body.name);
  }

  if (body.botToken !== undefined) {
    updates.push('bot_token = ?');
    values.push(body.botToken);
  }

  if (body.chatId !== undefined) {
    updates.push('chat_id = ?');
    values.push(body.chatId);
  }

  if (body.notificationTypes !== undefined) {
    updates.push('notification_types = ?');
    values.push(JSON.stringify(body.notificationTypes));
  }

  if (body.isEnabled !== undefined) {
    updates.push('is_enabled = ?');
    values.push(body.isEnabled ? 1 : 0);
  }

  if (updates.length === 0) {
    return useResponseError('没有可更新的字段', -1);
  }

  updates.push('updated_at = ?');
  values.push(new Date().toISOString());
  values.push(id);

  db.prepare(`UPDATE telegram_notification_configs SET ${updates.join(', ')} WHERE id = ?`).run(
    ...values,
  );

  const updated = db
    .prepare<{ id: number; name: string; bot_token: string; chat_id: string; notification_types: string; is_enabled: number; created_at: string; updated_at: string }>(
      'SELECT * FROM telegram_notification_configs WHERE id = ?',
    )
    .get(id);

  if (!updated) {
    return useResponseError('更新失败', -1);
  }

  return useResponseSuccess({
    id: updated.id,
    name: updated.name,
    botToken: updated.bot_token,
    chatId: updated.chat_id,
    notificationTypes: JSON.parse(updated.notification_types) as string[],
    isEnabled: updated.is_enabled === 1,
    createdAt: updated.created_at,
    updatedAt: updated.updated_at,
  });
});
