import { randomUUID } from 'node:crypto'
import { requireAdminAuth } from '../auth.js'
import { MAX_QUESTIONS } from '../config.js'
import { state } from '../state.js'
import { queueQuestionsWrite, queueDraftQuestionsWrite } from '../data.js'
import { buildQuestionAnsweredEmailTemplate, getResendFromAddress, getResendReplyToAddress, sendResendEmailWithRetry, getCanonicalBaseUrl } from '../email.js'
import { buildAbsoluteUrl } from '../helpers.js'
import { Resend } from 'resend'

function ensureDraftQuestions() {
  if (state.draftQuestions !== null) return
  state.draftQuestions = state.questions.slice(0, MAX_QUESTIONS)
}

export function register(app) {
  app.get('/api/questions', (_req, res) => {
    const sourceQuestions = state.draftQuestions ?? state.questions
    const publicQuestions = sourceQuestions
      .filter(q => q.isApproved === true && q.answer && q.answer.trim().length > 0)
      .sort((a, b) => {
        // Pinned questions always float to top
        if (a.pinned && !b.pinned) return -1
        if (!a.pinned && b.pinned) return 1
        return 0
      })
    res.json({ questions: publicQuestions })
  })

  app.get('/api/admin-questions', requireAdminAuth, (_req, res) => {
    res.json({ questions: state.draftQuestions ?? state.questions })
  })

  app.post('/api/admin-questions', requireAdminAuth, (req, res) => {
    const firstName = typeof req.body?.firstName === 'string' ? req.body.firstName.trim() : ''
    const email = typeof req.body?.email === 'string' ? req.body.email.trim() : ''
    const questionText = typeof req.body?.question === 'string' ? req.body.question.trim() : ''
    const answerText = typeof req.body?.answer === 'string' ? req.body.answer.trim() : ''
    const approveNow = req.body?.approve === true

    if (!firstName || firstName.length > 100) {
      res.status(400).json({ message: 'First name is required and must be 100 characters or fewer.' }); return
    }
    if (!questionText || questionText.length < 5 || questionText.length > 3000) {
      res.status(400).json({ message: 'Question must be between 5 and 3000 characters.' }); return
    }
    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      res.status(400).json({ message: 'If provided, email must be a valid email address.' }); return
    }
    if (answerText.length > 5000) {
      res.status(400).json({ message: 'Answer must be 5000 characters or fewer.' }); return
    }

    ensureDraftQuestions()
    const now = new Date().toISOString()
    const created = {
      id: randomUUID(),
      submittedAt: now,
      firstName,
      email,
      question: questionText,
      answer: answerText,
      answeredAt: answerText ? now : null,
      isApproved: approveNow,
      approvedAt: approveNow ? now : null,
    }

    state.draftQuestions.unshift(created)
    state.draftQuestions = state.draftQuestions.slice(0, MAX_QUESTIONS)
    queueDraftQuestionsWrite()

    res.status(201).json({ ok: true, question: created })
  })

  app.post('/api/admin-questions/:id/answer', requireAdminAuth, (req, res) => {
    const { id } = req.params
    const { answer } = req.body ?? {}

    if (!answer || typeof answer !== 'string' || answer.trim().length < 1 || answer.trim().length > 5000) {
      res.status(400).json({ message: 'Answer must be between 1 and 5000 characters.' }); return
    }

    ensureDraftQuestions()
    const question = state.draftQuestions.find(q => q.id === id)
    if (!question) {
      res.status(404).json({ message: 'Question not found.' }); return
    }

    question.answer = answer.trim()
    question.answeredAt = new Date().toISOString()
    queueDraftQuestionsWrite()

    res.json({ ok: true, question })
  })

  app.post('/api/admin-questions/:id/approve', requireAdminAuth, async (req, res) => {
    const { id } = req.params
    const { approved } = req.body ?? {}

    ensureDraftQuestions()
    const question = state.draftQuestions.find(q => q.id === id)
    if (!question) {
      res.status(404).json({ message: 'Question not found.' }); return
    }

    question.isApproved = approved === true
    question.approvedAt = approved === true ? new Date().toISOString() : null
    queueDraftQuestionsWrite()

    if (approved === true && question.notifyOnAnswer && question.email && question.answer) {
      try {
        const resend = new Resend(process.env.RESEND_API_KEY)
        const from = getResendFromAddress()
        const replyTo = getResendReplyToAddress()
        const baseUrl = getCanonicalBaseUrl()
        const questionUrl = buildAbsoluteUrl(baseUrl, `/questions#qa-${question.id}`)
        const template = buildQuestionAnsweredEmailTemplate({
          firstName: question.firstName,
          question: question.question,
          answer: question.answer,
          questionUrl,
        })
        await sendResendEmailWithRetry({
          resend,
          payload: { from, replyTo, to: question.email, subject: template.subject, text: template.text, html: template.html },
          context: `notify-on-answer:${question.id}`,
        })
      } catch (err) {
        console.error('[notify-on-answer] Failed to send notification email:', err?.message ?? err)
      }
    }

    res.json({ ok: true, question })
  })

  app.delete('/api/admin-questions/:id', requireAdminAuth, (req, res) => {
    const { id } = req.params
    ensureDraftQuestions()
    const index = state.draftQuestions.findIndex(q => q.id === id)

    if (index === -1) {
      res.status(404).json({ message: 'Question not found.' }); return
    }

    state.draftQuestions.splice(index, 1)
    queueDraftQuestionsWrite()

    res.json({ ok: true })
  })

  // Anonymous upvote — no auth required, lightweight increment
  app.post('/api/questions/:id/upvote', (req, res) => {
    const { id } = req.params
    // Look in live questions first, then draft
    const liveQ = state.questions.find(q => q.id === id && q.isApproved === true)
    const draftQ = state.draftQuestions ? state.draftQuestions.find(q => q.id === id) : null
    const question = liveQ ?? draftQ
    if (!question) {
      res.status(404).json({ message: 'Question not found.' }); return
    }
    question.upvotes = ((question.upvotes ?? 0) + 1)
    if (liveQ) queueQuestionsWrite()
    if (draftQ) queueDraftQuestionsWrite()
    res.json({ ok: true, upvotes: question.upvotes })
  })

  // Admin: pin / unpin a question
  app.post('/api/admin-questions/:id/pin', requireAdminAuth, (req, res) => {
    const { id } = req.params
    ensureDraftQuestions()
    const question = state.draftQuestions.find(q => q.id === id)
    if (!question) { res.status(404).json({ message: 'Question not found.' }); return }
    question.pinned = true
    queueDraftQuestionsWrite()
    res.json({ ok: true, question })
  })

  app.delete('/api/admin-questions/:id/pin', requireAdminAuth, (req, res) => {
    const { id } = req.params
    ensureDraftQuestions()
    const question = state.draftQuestions.find(q => q.id === id)
    if (!question) { res.status(404).json({ message: 'Question not found.' }); return }
    question.pinned = false
    queueDraftQuestionsWrite()
    res.json({ ok: true, question })
  })
}
