import { Request, Response } from 'express'
import { rateLimit } from '../lib/rate-limit.js'
import { sendSubscriptionEmail } from '../lib/email.js'

interface SubscriptionData {
  name: string
  email: string
}

const validateEmail = (email: string): boolean => {
  const pattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  return pattern.test(email)
}

const validateInput = (data: SubscriptionData): { isValid: boolean; error?: string } => {
  if (!data.name || data.name.length < 2 || data.name.length > 50) {
    return { isValid: false, error: 'Invalid name length' }
  }

  if (!data.email || !validateEmail(data.email)) {
    return { isValid: false, error: 'Invalid email format' }
  }

  return { isValid: true }
}

const sanitizeInput = (input: string): string => {
  return input
    .trim()
    .replace(/[<>]/g, '')
    .slice(0, 1000)
}

export async function POST(req: Request, res: Response) {
  try {
    if (!req.body) {
      return res.status(400).json({
        success: false,
        message: 'Request body is missing'
      })
    }

    const rateLimitResult = await rateLimit(req)
    if (!rateLimitResult.success) {
      return res.status(429).json({
        success: false,
        message: 'Too many requests. Please try again later.'
      })
    }

    const data: SubscriptionData = req.body
    const validation = validateInput(data)
    
    if (!validation.isValid) {
      return res.status(400).json({
        success: false,
        message: validation.error
      })
    }

    const sanitizedData = {
      name: sanitizeInput(data.name),
      email: sanitizeInput(data.email)
    }

    await sendSubscriptionEmail(sanitizedData)

    return res.status(200).json({
      success: true,
      message: 'Subscription successful'
    })
    
  } catch (error) {
    console.error('Error processing subscription:', error)
    return res.status(500).json({
      success: false,
      message: 'Failed to process subscription. Please try again later.'
    })
  }
}
