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

async function postToSlack(blocks: object[]): Promise<boolean> {
  if (!SLACK_WEBHOOK_URL) {
    console.warn('[notification:slack] SLACK_PILOT_WEBHOOK_URL not set, skipping');
    return false;
  }
  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) {
      console.error(`[notification:slack] HTTP ${res.status}: ${await res.text()}`);
      return false;
    }
    return true;
  } catch (err) {
    console.error('[notification:slack] fetch error:', (err as Error).message);
    return false;
  }
}

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}`,
        },
      ],
    },
  ];

  const ok = await postToSlack(blocks);
  if (ok) console.log(`[notification:slack] pilot alert sent for request ${payload.requestId}`);
  return ok;
}

export interface ChatEscalationPayload {
  trigger: string;
  conversation: Array<{ role: string; content: string }>;
  userAgent?: string;
}

export async function sendChatEscalationAlert(payload: ChatEscalationPayload): Promise<boolean> {
  const preview = payload.conversation
    .slice(-6)
    .map(m => `*${m.role === 'user' ? 'Visitor' : 'Bot'}:* ${m.content.slice(0, 300)}`)
    .join('\n');

  const blocks = [
    {
      type: 'header',
      text: { type: 'plain_text', text: '💬 Chat Widget — Visitor Needs Help', emoji: true },
    },
    {
      type: 'section',
      text: { type: 'mrkdwn', text: `*Trigger phrase:* \`${payload.trigger}\`` },
    },
    {
      type: 'section',
      text: { type: 'mrkdwn', text: `*Recent conversation:*\n${preview}` },
    },
    {
      type: 'context',
      elements: [{ type: 'mrkdwn', text: payload.userAgent ? `UA: ${payload.userAgent.slice(0, 120)}` : 'UA: unknown' }],
    },
  ];

  return postToSlack(blocks);
}

export interface SupportEmailPayload {
  uid: number;
  subject: string;
  from: string;
  date: string;
}

export async function sendSupportEmailAlert(payload: SupportEmailPayload): Promise<boolean> {
  const blocks = [
    {
      type: 'header',
      text: { type: 'plain_text', text: '📧 New Email → support@squaremcp.com', emoji: true },
    },
    {
      type: 'section',
      fields: [
        { type: 'mrkdwn', text: `*From:*\n${payload.from}` },
        { type: 'mrkdwn', text: `*Date:*\n${payload.date}` },
      ],
    },
    {
      type: 'section',
      text: { type: 'mrkdwn', text: `*Subject:*\n${payload.subject}` },
    },
  ];

  return postToSlack(blocks);
}
