import { getSlackConfig, saveSlackConfig, removeSlackConfig, getDeliveryLog, appendDelivery, } from '../storage/slack-store.js';
import { buildManualPayload, dispatchToSlack } from '../engine/slack-dispatcher.js';
// ---------------------------------------------------------------------------
// configure_slack handler
// ---------------------------------------------------------------------------
export async function handleConfigureSlack(input) {
    const now = new Date().toISOString();
    const existing = await getSlackConfig(input.projectPath);
    const config = {
        webhookUrl: input.webhookUrl,
        channel: input.channel,
        projectPath: input.projectPath,
        enabled: true,
        createdAt: existing?.createdAt ?? now,
        updatedAt: now,
    };
    await saveSlackConfig(input.projectPath, config);
    const lines = [
        'Slack configured successfully.',
        '',
        '| Field | Value |',
        '|-------|-------|',
        `| Webhook | ${maskUrl(input.webhookUrl)} |`,
        `| Channel | ${input.channel ?? '(default)'} |`,
        `| Enabled | Yes |`,
        `| Updated | ${now} |`,
    ];
    return { content: [{ type: 'text', text: lines.join('\n') }] };
}
// ---------------------------------------------------------------------------
// slack_notify handler
// ---------------------------------------------------------------------------
export async function handleSlackNotify(input) {
    const config = await getSlackConfig(input.projectPath);
    if (config?.enabled !== true) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Error: Slack is not configured for this project. Run configure_slack first.',
                },
            ],
            isError: true,
        };
    }
    const payload = buildManualPayload(input.message, input.specId);
    const delivery = {
        id: `dlv-${Date.now()}`,
        sentAt: new Date().toISOString(),
        status: 'sent',
        specId: input.specId,
        eventType: 'manual',
    };
    try {
        await dispatchToSlack(config.webhookUrl, payload);
    }
    catch (err) {
        delivery.status = 'failed';
        delivery.error = err instanceof Error ? err.message : String(err);
        await appendDelivery(input.projectPath, delivery);
        return {
            content: [
                {
                    type: 'text',
                    text: `Error sending Slack notification: ${delivery.error}`,
                },
            ],
            isError: true,
        };
    }
    await appendDelivery(input.projectPath, delivery);
    return {
        content: [
            {
                type: 'text',
                text: `Slack notification sent successfully.${input.specId !== undefined ? ` [${input.specId}]` : ''}\n\n> ${input.message}`,
            },
        ],
    };
}
// ---------------------------------------------------------------------------
// slack_status handler
// ---------------------------------------------------------------------------
export async function handleSlackStatus(input) {
    const config = await getSlackConfig(input.projectPath);
    if (config === null) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Slack is not configured for this project. Run configure_slack to set up notifications.',
                },
            ],
        };
    }
    const deliveries = await getDeliveryLog(input.projectPath);
    const lines = [
        '**Slack Configuration**',
        '',
        '| Field | Value |',
        '|-------|-------|',
        `| Webhook | ${maskUrl(config.webhookUrl)} |`,
        `| Channel | ${config.channel ?? '(default)'} |`,
        `| Enabled | ${config.enabled ? 'Yes' : 'No'} |`,
        `| Created | ${config.createdAt} |`,
        `| Updated | ${config.updatedAt} |`,
        '',
        `**Delivery Log** (last ${deliveries.length})`,
        '',
    ];
    if (deliveries.length === 0) {
        lines.push('No deliveries yet.');
    }
    else {
        for (const d of deliveries) {
            const spec = d.specId !== undefined ? ` [${d.specId}]` : '';
            const err = d.error !== undefined ? ` — ${d.error}` : '';
            lines.push(`- ${d.sentAt.slice(0, 19)} | ${d.status}${spec}${err}`);
        }
    }
    return { content: [{ type: 'text', text: lines.join('\n') }] };
}
// ---------------------------------------------------------------------------
// remove_slack handler
// ---------------------------------------------------------------------------
export async function handleRemoveSlack(input) {
    const config = await getSlackConfig(input.projectPath);
    if (config === null) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Slack is not configured for this project — nothing to remove.',
                },
            ],
        };
    }
    await removeSlackConfig(input.projectPath);
    return {
        content: [
            {
                type: 'text',
                text: 'Slack configuration removed. Notifications are disabled.',
            },
        ],
    };
}
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
function maskUrl(url) {
    try {
        const parsed = new URL(url);
        const path = parsed.pathname;
        const masked = path.length > 8 ? `${path.slice(0, 4)}...${path.slice(-4)}` : '***';
        return `${parsed.protocol}//${parsed.host}${masked}`;
    }
    catch {
        return '***';
    }
}
//# sourceMappingURL=slack-handler.js.map