const SLACK_WEBHOOK_URL = process.env['SLACK_PILOT_WEBHOOK_URL'] ?? '';

export interface PilotAlertPayload {
  requestId: string;
  name: string;
  email: string;
  company: string;
  role: string;
  use_case: string;
  timeline: string;
  systems: string;
  requirements: string;
  source: string;
  ipAddress: string;
}

export async function sendSlackAlert(payload: PilotAlertPayload): Promise<boolean> {
  if (!SLACK_WEBHOOK_URL) {
    console.warn('[notification:slack] SLACK_PILOT_WEBHOOK_URL not set, skipping');
    return false;
  }

  const blocks = [
    {
      type: 'header',
      text: {
        type: 'plain_text',
        text: '🚨 New SquareMCP Pilot Request',
        emoji: true,
      },
    },
    {
      type: 'section',
      fields: [
        { type: 'mrkdwn', text: `*Name:*\n${payload.name}` },
        { type: 'mrkdwn', text: `*Company:*\n${payload.company}` },
        { type: 'mrkdwn', text: `*Email:*\n${payload.email}` },
        { type: 'mrkdwn', text: `*Role:*\n${payload.role}` },
        { type: 'mrkdwn', text: `*Timeline:*\n${payload.timeline}` },
        { type: 'mrkdwn', text: `*Source:*\n${payload.source}` },
      ],
    },
    {
      type: 'section',
      text: {
        type: 'mrkdwn',
        text: `*Use Case:*\n${payload.use_case}`,
      },
    },
    {
      type: 'section',
      text: {
        type: 'mrkdwn',
        text: `*Systems:*\n${payload.systems || '_None specified_'}`,
      },
    },
    {
      type: 'section',
      text: {
        type: 'mrkdwn',
        text: `*Requirements:*\n${payload.requirements || '_None specified_'}`,
      },
    },
    {
      type: 'context',
      elements: [
        {
          type: 'mrkdwn',
          text: `Request ID: \`${payload.requestId}\` | IP: ${payload.ipAddress}`,
        },
      ],
    },
  ];

  try {
    const res = await fetch(SLACK_WEBHOOK_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ blocks }),
      signal: AbortSignal.timeout(10_000),
    });

    if (!res.ok) {
      const text = await res.text();
      console.error(`[notification:slack] HTTP ${res.status}: ${text}`);
      return false;
    }

    console.log(`[notification:slack] alert sent for request ${payload.requestId}`);
    return true;
  } catch (err) {
    console.error('[notification:slack] fetch error:', (err as Error).message);
    return false;
  }
}
