import type { SlackChannelConfig } from '../types.js';
import type { SendResult } from './email.js';

export interface SlackMessage {
  text: string;
  channel?: string;
  username?: string;
}

export async function sendSlackMessage(
  message: SlackMessage,
  config: SlackChannelConfig
): Promise<SendResult> {
  if (!config.webhookUrl) {
    return { success: false, error: 'Slack webhook URL not configured' };
  }

  try {
    const response = await fetch(config.webhookUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        text: message.text,
        channel: message.channel || config.defaultChannel,
        username: message.username,
      }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      return { success: false, error: `Slack error ${response.status}: ${errorText}` };
    }

    return {
      success: true,
      messageId: `slack_${crypto.randomUUID()}`,
    };
  } catch (err: unknown) {
    return { success: false, error: err instanceof Error ? err.message : String(err) };
  }
}
