import { LISTING_CATEGORIES } from '@/data/listing-field-options'
import type { ListingCategoryId } from '@/data/listing-field-options'
import { getSiteOrigin } from '@/lib/site-origin'
import { getMailFrom, getMailReplyTo, getSmtpTransport, isSmtpConfigured } from '@/lib/email/smtp'

function escapeHtml(text: string): string {
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
}

function categoryLabel(categoryId: ListingCategoryId): string {
  return LISTING_CATEGORIES.find((c) => c.id === categoryId)?.label ?? categoryId
}

export type ListingPublishedEmailInput = {
  to: string
  title: string
  slug: string
  categoryId: ListingCategoryId
  durationDays: number
  contactName: string
}

export type ListingPublishedEmailResult = { sent: true } | { sent: false; reason: 'disabled' | 'error'; message?: string }

/**
 * Potwierdzenie publikacji ogłoszenia (SMTP @twojalodka.pl z hostingu).
 * Wymaga SMTP_HOST, SMTP_USER, SMTP_PASS — brak konfiguracji nie blokuje zapisu ogłoszenia.
 */
export async function sendListingPublishedConfirmation(
  input: ListingPublishedEmailInput,
): Promise<ListingPublishedEmailResult> {
  if (!isSmtpConfigured()) {
    return { sent: false, reason: 'disabled' }
  }

  const transport = getSmtpTransport()
  if (!transport) {
    return { sent: false, reason: 'disabled' }
  }

  const to = input.to.trim().toLowerCase()
  if (!to) {
    return { sent: false, reason: 'error', message: 'Brak adresu odbiorcy.' }
  }

  const origin = getSiteOrigin()
  const listingUrl = `${origin}/sklep/${encodeURIComponent(input.slug)}`
  const cat = categoryLabel(input.categoryId)
  const safeTitle = escapeHtml(input.title.trim())
  const safeName = escapeHtml(input.contactName.trim() || '—')

  const subject = `Potwierdzenie publikacji ogłoszenia — ${input.title.trim().slice(0, 80)}`

  const text = [
    'Dzień dobry,',
    '',
    input.contactName.trim() ? `Witaj ${input.contactName.trim()},` : '',
    '',
    'Twoje ogłoszenie zostało opublikowane na Twoja Łódka.',
    '',
    `Tytuł: ${input.title.trim()}`,
    `Kategoria: ${cat}`,
    `Czas publikacji: ${input.durationDays} dni`,
    '',
    `Podgląd ogłoszenia: ${listingUrl}`,
    '',
    'Jeśli to nie Ty publikowałeś ogłoszenie, skontaktuj się z nami: kontakt@twojalodka.pl',
    '',
    '— Twoja Łódka',
  ]
    .filter((line, i, arr) => !(line === '' && arr[i - 1] === ''))
    .join('\n')

  const html = `<!DOCTYPE html>
<html lang="pl">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width"></head>
<body style="font-family:system-ui,-apple-system,sans-serif;line-height:1.5;color:#111827;max-width:36rem;margin:0 auto;padding:24px">
  <p style="margin:0 0 16px">Dzień dobry${input.contactName.trim() ? `, <strong>${safeName}</strong>` : ''},</p>
  <p style="margin:0 0 16px">Twoje ogłoszenie zostało <strong>opublikowane</strong> na <a href="${origin}" style="color:#2563eb">Twoja Łódka</a>.</p>
  <table style="width:100%;border-collapse:collapse;margin:0 0 20px;font-size:15px">
    <tr><td style="padding:8px 0;color:#6b7280;vertical-align:top">Tytuł</td><td style="padding:8px 0"><strong>${safeTitle}</strong></td></tr>
    <tr><td style="padding:8px 0;color:#6b7280">Kategoria</td><td style="padding:8px 0">${escapeHtml(cat)}</td></tr>
    <tr><td style="padding:8px 0;color:#6b7280">Publikacja</td><td style="padding:8px 0">${input.durationDays} dni</td></tr>
  </table>
  <p style="margin:0 0 24px">
    <a href="${listingUrl}" style="display:inline-block;background:#2563eb;color:#fff;text-decoration:none;padding:12px 20px;border-radius:8px;font-weight:600">Zobacz ogłoszenie</a>
  </p>
  <p style="margin:0;font-size:13px;color:#6b7280">Jeśli to nie Ty publikowałeś ogłoszenie, napisz na <a href="mailto:kontakt@twojalodka.pl" style="color:#2563eb">kontakt@twojalodka.pl</a>.</p>
</body>
</html>`

  try {
    const info = await transport.sendMail({
      from: getMailFrom(),
      to,
      replyTo: getMailReplyTo(),
      subject,
      html,
      text,
    })

    if (!info.messageId) {
      return { sent: false, reason: 'error', message: 'Serwer SMTP nie zwrócił ID wiadomości.' }
    }

    return { sent: true }
  } catch (e) {
    console.error('smtp listing confirmation', e)
    return {
      sent: false,
      reason: 'error',
      message: e instanceof Error ? e.message : 'Nieznany błąd wysyłki.',
    }
  }
}
