export type InquiryMail = {
  requestId: string;
  name: string;
  email: string;
  company: string;
  phone: string;
  message: string;
};
export type MailEnvironment = {
  MAIL_RELAY_URL?: string;
  MAIL_RELAY_HMAC_KEY?: string;
};
export type NotificationStatus = 'not_configured' | 'sent' | 'failed';

export async function notifyInquiry(
  config: MailEnvironment,
  inquiry: InquiryMail,
  request: typeof fetch = fetch,
): Promise<NotificationStatus> {
  if (!config.MAIL_RELAY_URL || !config.MAIL_RELAY_HMAC_KEY) return 'not_configured';
  try {
    const url = new URL(config.MAIL_RELAY_URL);
    if (url.protocol !== 'https:' || url.username || url.password) return 'failed';
    const body = JSON.stringify(inquiry);
    const timestamp = Math.floor(Date.now() / 1000).toString();
    const encoder = new TextEncoder();
    const key = await crypto.subtle.importKey(
      'raw', encoder.encode(config.MAIL_RELAY_HMAC_KEY),
      { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
    );
    const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(`${timestamp}\n${body}`));
    const hex = Array.from(new Uint8Array(signature), byte => byte.toString(16).padStart(2, '0')).join('');
    const response = await request(url.toString(), {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Cas7-Timestamp': timestamp,
        'X-Cas7-Signature': hex,
      },
      body,
      redirect: 'manual',
      signal: AbortSignal.timeout(45000),
    });
    if (response.status !== 200) return 'failed';
    const result = await response.json() as { ok?: boolean; status?: string };
    return result.ok === true && result.status === 'sent' ? 'sent' : 'failed';
  } catch {
    return 'failed';
  }
}
