import express from 'express'
import dotenv from 'dotenv'
import { POST as handleContact } from './src/api/contact.js'
import { POST as handleSubscribe } from './src/api/subscribe.js'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'

dotenv.config()

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const app = express()
app.use(express.json())

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
  res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
  next()
})

app.use(express.static(join(__dirname, 'dist')))

app.post('/contact', async (req, res) => {
  try {
    const response = await handleContact(req)
    res.status(response.status).json(response.body)
  } catch {
    res.status(500).json({ 
      success: false, 
      message: 'Internal server error'
    })
  }
})

app.post('/subscribe', async (req, res) => {
  try {
    await handleSubscribe(req, res)
  } catch (error) {
    console.error('Server error in subscribe route:', error)
    res.status(500).json({ 
      success: false, 
      message: 'Internal server error'
    })
  }
})

app.get('*', (req, res) => {
  res.sendFile(join(__dirname, 'dist', 'index.html'))
})

const PORT = process.env.PORT || 804

app.listen(PORT, () => {
  console.info(`Server running on port ${PORT}`)
})
