import { stat } from 'node:fs/promises'
import { requireAdminAuth } from '../auth.js'
import { TITUS_STUDY_FILE, TITUS_STUDY_DOWNLOAD_NAME } from '../config.js'
import { state } from '../state.js'
import {
  loadSiteContentFile,
  queueContactSubmissionsWrite,
  normalizeContactEmailStatus,
  normalizeMessageType,
  incrementDownloadCount,
} from '../data.js'
import {
  createTitusDownloadToken,
  consumeTitusDownloadToken,
  sanitizeUrl,
} from '../study-helpers.js'
import { syncContactToResend } from '../email.js'
import { DATA_FILE, MAX_CONTACT_SUBMISSIONS } from '../config.js'
import { randomUUID } from 'node:crypto'

const downloadHits = new Map()

function studyDownloadRateLimit(req, res, next) {
  const ip = req.ip ?? 'unknown'
  const now = Date.now()
  const windowMs = 10 * 60 * 1000
  const entry = downloadHits.get(ip) ?? { count: 0, start: now }
  if (now - entry.start > windowMs) { entry.count = 0; entry.start = now }
  entry.count += 1
  downloadHits.set(ip, entry)
  // Prune stale entries to prevent unbounded growth
  if (downloadHits.size > 5000) {
    const cutoff = now - windowMs
    for (const [k, v] of downloadHits) { if (v.start < cutoff) downloadHits.delete(k) }
  }
  if (entry.count > 10) {
    res.status(429).json({ message: 'Too many download requests. Please wait a few minutes.' })
    return
  }
  next()
}

function addContactSubmission({ name, email, message, messageType, subscribe }) {
  const wantsWelcome = subscribe === true
  const submission = {
    id: randomUUID(),
    submittedAt: new Date().toISOString(),
    name,
    email,
    message,
    messageType: normalizeMessageType(messageType),
    subscribe: wantsWelcome,
    archived: false,
    emailStatus: normalizeContactEmailStatus(null, wantsWelcome),
  }
  state.contactSubmissions.unshift(submission)
  state.contactSubmissions = state.contactSubmissions.slice(0, MAX_CONTACT_SUBMISSIONS)
  queueContactSubmissionsWrite()
  return submission
}

export function register(app) {
  app.post('/api/study-downloads/titus', studyDownloadRateLimit, async (req, res) => {
    try {
      const { firstName, lastName, email, subscribe, _honey } = req.body ?? {}

      if (_honey) { res.json({ ok: true }); return }

      if (!firstName || typeof firstName !== 'string' || firstName.trim().length < 1 || firstName.trim().length > 100) {
        res.status(400).json({ message: 'First name is required.' }); return
      }
      if (!lastName || typeof lastName !== 'string' || lastName.trim().length < 1 || lastName.trim().length > 100) {
        res.status(400).json({ message: 'Last name is required.' }); return
      }
      if (!email || typeof email !== 'string' || !/^[a-zA-Z0-9._%+\-]{1,64}@[a-zA-Z0-9.\-]{1,253}\.[a-zA-Z]{2,}$/.test(email.trim())) {
        res.status(400).json({ message: 'A valid email address is required.' }); return
      }

      const published = await loadSiteContentFile(DATA_FILE)
      const configuredDownloadUrl = sanitizeUrl(published?.siteContent?.studyGuideDownloadUrl)

      if (!configuredDownloadUrl) {
        try {
          await stat(TITUS_STUDY_FILE)
        } catch {
          res.status(503).json({ message: 'The primary study guide download URL is not configured yet.' }); return
        }
      }

      const trimmedFirstName = firstName.trim()
      const trimmedLastName = lastName.trim()
      const trimmedName = `${trimmedFirstName} ${trimmedLastName}`.trim()
      const trimmedEmail = email.trim()
      const wantsSubscribe = subscribe !== false

      addContactSubmission({ name: trimmedName, email: trimmedEmail, message: 'Requested Titus study download.', messageType: 'general', subscribe: wantsSubscribe })

      if (wantsSubscribe) {
        await syncContactToResend(trimmedName, trimmedEmail)
      }

      incrementDownloadCount('titus-study')

      if (configuredDownloadUrl) {
        res.json({ ok: true, downloadUrl: configuredDownloadUrl }); return
      }

      const token = createTitusDownloadToken(trimmedEmail)
      res.json({ ok: true, downloadUrl: `/api/study-downloads/titus/file?token=${encodeURIComponent(token)}` })
    } catch (err) {
      console.error('[study-download] request error:', err)
      res.status(500).json({ message: 'Failed to process your request. Please try again.' })
    }
  })

  app.get('/api/study-downloads/titus/file', async (req, res) => {
    const token = typeof req.query?.token === 'string' ? req.query.token : ''
    if (!token || !consumeTitusDownloadToken(token)) {
      res.status(403).json({ message: 'Invalid or expired download link. Submit the form again.' }); return
    }

    try {
      await stat(TITUS_STUDY_FILE)
      res.download(TITUS_STUDY_FILE, TITUS_STUDY_DOWNLOAD_NAME)
    } catch {
      res.status(503).json({ message: 'The Titus study file is not configured yet.' })
    }
  })

  app.post('/api/resource-download', studyDownloadRateLimit, async (req, res) => {
    try {
      const { resourceId, firstName, lastName, email, subscribe, _honey } = req.body ?? {}

      if (_honey) { res.json({ ok: true }); return }

      if (!resourceId || typeof resourceId !== 'string') {
        res.status(400).json({ message: 'Resource ID is required.' }); return
      }

      const published = await loadSiteContentFile(DATA_FILE)
      const siteContent = published?.siteContent

      function resolveResourceFromId(id) {
        if (!siteContent || typeof siteContent !== 'object') return null
        const customResources = Array.isArray(siteContent.customLinks)
          ? siteContent.customLinks.filter(link => link?.placement === 'resources')
          : []
        if (id.startsWith('custom:')) {
          const customId = id.slice('custom:'.length)
          const match = customResources.find(link => link.id === customId)
          return match ? { label: match.label, url: match.url } : null
        }
        if (id.startsWith('archived:')) {
          const [, seriesId, ...linkIdParts] = id.split(':')
          const linkId = linkIdParts.join(':')
          const archivedSeries = Array.isArray(siteContent.archivedSeries) ? siteContent.archivedSeries : []
          const series = archivedSeries.find(item => item.id === seriesId)
          const link = Array.isArray(series?.resourceLinks) ? series.resourceLinks.find(item => item.id === linkId) : null
          return link ? { label: link.label || series?.title, url: link.url } : null
        }
        const customMatch = customResources.find(link => link.id === id)
        if (customMatch) return { label: customMatch.label, url: customMatch.url }
        const archivedSeries = Array.isArray(siteContent.archivedSeries) ? siteContent.archivedSeries : []
        for (const series of archivedSeries) {
          if (!Array.isArray(series?.resourceLinks)) continue
          const link = series.resourceLinks.find(item => item.id === id)
          if (link) return { label: link.label || series?.title, url: link.url }
        }
        return null
      }

      const resource = resolveResourceFromId(resourceId)
      if (!resource || typeof resource.url !== 'string' || !resource.url.trim()) {
        res.status(400).json({ message: 'Resource not found.' }); return
      }

      if (!firstName || typeof firstName !== 'string' || firstName.trim().length < 1 || firstName.trim().length > 100) {
        res.status(400).json({ message: 'First name is required.' }); return
      }
      if (!lastName || typeof lastName !== 'string' || lastName.trim().length < 1 || lastName.trim().length > 100) {
        res.status(400).json({ message: 'Last name is required.' }); return
      }
      if (!email || typeof email !== 'string' || !/^[a-zA-Z0-9._%+\-]{1,64}@[a-zA-Z0-9.\-]{1,253}\.[a-zA-Z]{2,}$/.test(email.trim())) {
        res.status(400).json({ message: 'A valid email address is required.' }); return
      }

      const trimmedFirstName = firstName.trim()
      const trimmedLastName = lastName.trim()
      const trimmedName = `${trimmedFirstName} ${trimmedLastName}`.trim()
      const trimmedEmail = email.trim()
      const wantsSubscribe = subscribe !== false

      addContactSubmission({
        name: trimmedName,
        email: trimmedEmail,
        message: `Requested resource download: ${resource.label ?? resource.url}`,
        messageType: 'general',
        subscribe: wantsSubscribe,
      })

      if (wantsSubscribe) {
        await syncContactToResend(trimmedName, trimmedEmail)
      }

      incrementDownloadCount(`resource:${resourceId}`)
      res.json({ ok: true, downloadUrl: resource.url.trim() })
    } catch (err) {
      console.error('[resource-download] request error:', err)
      res.status(500).json({ message: 'Failed to process your request. Please try again.' })
    }
  })

  app.get('/api/admin-download-stats', requireAdminAuth, (_req, res) => {
    res.json({ counts: state.downloadCounts })
  })
}
