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

interface FormData {
  name: string
  email: string
  service: string
  message: 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: FormData): { 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' }
  }

  if (!data.service) {
    return { isValid: false, error: 'Service selection required' }
  }

  if (!data.message || data.message.length < 10 || data.message.length > 1000) {
    return { isValid: false, error: 'Invalid message length' }
  }

  return { isValid: true }
}

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

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

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

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

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

    await sendEmail(sanitizedData)

    return {
      status: 200,
      body: {
        success: true,
        message: 'Message sent successfully'
      }
    }
    
  } catch (error) {
    return {
      status: 500,
      body: {
        success: false,
        message: 'Failed to send message. Please try again later.'
      }
    }
  }
}
