import { prisma } from '../../utils/index.js';
import { OSNotificationChannel } from './os-channel.js';
import { FeishuChannel } from './feishu-channel.js';
import { getDefaultNotificationSettings } from './defaults.js';
export class NotificationService {
    osChannel = new OSNotificationChannel();
    async notify(event) {
        const settings = await this.getSettings();
        // 渲染模板
        const rendered = this.renderTemplate(event, settings);
        const sends = [];
        if (settings.osNotificationEnabled) {
            sends.push(this.osChannel.send({
                ...event,
                title: rendered.title,
                body: rendered.body,
            }));
        }
        if (settings.thirdPartyChannel === 'feishu' && settings.feishuWebhookUrl) {
            sends.push(new FeishuChannel(settings.feishuWebhookUrl, settings.thirdPartyBaseUrl ?? undefined).send({
                ...event,
                title: rendered.title,
                body: rendered.body,
            }));
        }
        if (sends.length === 0)
            return;
        const results = await Promise.allSettled(sends);
        for (const result of results) {
            if (result.status === 'rejected') {
                console.error('[NotificationService] Channel failed:', result.reason);
            }
        }
    }
    renderTemplate(event, settings) {
        let title = event.title;
        let body = event.body;
        if (event.type === 'task_in_review') {
            title = settings.taskInReviewTitleTemplate || event.title;
            body = settings.taskInReviewBodyTemplate || event.body;
        }
        // 模板变量替换
        const vars = {
            taskTitle: event.metadata?.taskTitle || '',
            taskId: event.metadata?.taskId || '',
            projectId: event.metadata?.projectId || '',
            projectName: event.metadata?.projectName || '',
            status: event.metadata?.status || '',
        };
        for (const [key, value] of Object.entries(vars)) {
            const pattern = new RegExp(`\\{${key}\\}`, 'g');
            title = title.replace(pattern, value);
            body = body.replace(pattern, value);
        }
        return { title, body };
    }
    async getSettings() {
        const settings = await prisma.notificationSettings.findUnique({
            where: { id: 'singleton' },
        });
        if (settings) {
            return settings;
        }
        const appSettings = await prisma.appSettings.findUnique({
            where: { id: 'singleton' },
        });
        return getDefaultNotificationSettings(appSettings?.locale === 'en' ? 'en' : 'zh-CN');
    }
    async testChannel(channel, webhookUrl, baseUrl) {
        if (channel === 'feishu') {
            const feishu = new FeishuChannel(webhookUrl, baseUrl);
            await feishu.send({
                type: 'task_in_review',
                title: 'Agent Tower 测试通知',
                body: '🎉 飞书通知配置成功！点击下方按钮可跳转到任务页面。',
                metadata: { taskId: 'test-task-id', projectId: 'test-project-id' },
            });
        }
        else {
            throw new Error(`Unknown channel: ${channel}`);
        }
    }
}
//# sourceMappingURL=notification.service.js.map