import { sendSlackAlert, type PilotAlertPayload } from './slack.js';

const TEST_PATTERNS = {
  email: [/@example\.com$/i],
  name: [/e2e/i, /smoke test/i, /qa test/i, /browser test/i],
  company: [/qa check/i, /qa corp/i, /^squaremcp\s*(e2e|test|browser)/i],
};

function isTestSubmission(body: {
  name: string;
  email: string;
  company: string;
}): boolean {
  if (TEST_PATTERNS.email.some((p) => p.test(body.email))) return true;
  if (TEST_PATTERNS.name.some((p) => p.test(body.name))) return true;
  if (TEST_PATTERNS.company.some((p) => p.test(body.company))) return true;
  return false;
}

interface PilotRequestBody {
  name: string;
  email: string;
  company: string;
  role: string;
  use_case: string;
  timeline: string;
  systems: string;
  requirements: string;
}

export async function notifyNewPilotRequest(
  body: PilotRequestBody,
  requestId: string,
  req: { get: (header: string) => string | undefined; ip?: string; socket?: { remoteAddress?: string } }
): Promise<void> {
  if (isTestSubmission(body)) {
    console.log(`[notification] skipped test submission: ${body.email}`);
    return;
  }

  const payload: PilotAlertPayload = {
    requestId,
    name: body.name,
    email: body.email,
    company: body.company,
    role: body.role,
    use_case: body.use_case,
    timeline: body.timeline,
    systems: body.systems,
    requirements: body.requirements,
    source: req.get('origin') || req.get('host') || 'unknown',
    ipAddress: req.ip || req.socket?.remoteAddress || 'unknown',
  };

  // Fire-and-forget — don't block the HTTP response
  sendSlackAlert(payload).catch((err) =>
    console.error('[notification] slack error:', err)
  );
}
