import { Notifier, NotifyParams, NotifyResult, NotifierParam } from './notifier.types';

const params: NotifierParam[] = [
  { key: 'webhook_url', label: 'Webhook URL', type: 'url', required: true, placeholder: 'https://open.feishu.cn/open-apis/bot/v2/hook/xxx' },
  
];

export const larkNotifier: Notifier = {
  name: 'lark',
  label: '\u98de\u4e66/Lark',
  params,
  async notify(p: NotifyParams): Promise<NotifyResult> {
    try {
      const level = p.level || 'info';
      const template = level === 'error' ? 'red' : level === 'warn' ? 'orange' : 'blue';
      const resp = await fetch(p.webhook_url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          msg_type: 'interactive',
          card: {
            header: { title: { tag: 'plain_text', content: p.title || 'CloudSearch' }, template },
            elements: [
              { tag: 'div', text: { tag: 'lark_md', content: p.content || '' } },
              { tag: 'note', elements: [{ tag: 'plain_text', content: 'CloudSearch \u00b7 ' + new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }) }] }
            ],
          },
        }),
      });
      if (resp.ok) return { success: true, message: '\u98de\u4e66\u63a8\u9001\u6210\u529f' };
      const text = await resp.text();
      return { success: false, message: text.slice(0, 150) };
    } catch (err: any) {
      return { success: false, message: err.message };
    }
  },
};
