import 'dotenv/config';
import express, { Request, Response } from 'express';
import cors from 'cors';
import path from 'path';
import { createCheckoutSession } from './routes/checkout';
import { getCheckoutSession } from './routes/sessions';
import { getServices } from './routes/services';
import { handleWebhook } from './routes/webhook';
import { postContact } from './routes/contact';
import { stripe } from './lib/stripe';

const app = express();
const PORT = process.env.PORT || 3000;

// Middleware
app.use(cors());
app.use(express.json());

// Serve static files from public directory
const publicPath = path.join(__dirname, '../public');

app.get('/', (_req, res) => {
  res.sendFile(path.join(publicPath, 'pages/index.html'));
});

// Legacy URLs at site root (e.g. /checkout.html) → /pages/...
app.get(/^\/[^/]+\.html$/, (req, res) => {
  if (req.path === '/index.html') {
    res.redirect(301, '/');
    return;
  }
  res.redirect(301, `/pages${req.path}`);
});

app.use(express.static(publicPath));

// API Routes
app.post('/api/create-checkout-session', createCheckoutSession);
app.get('/api/checkout-session/:sessionId', getCheckoutSession);
app.get('/api/services', getServices);
app.post('/api/contact', postContact);

// Webhook endpoint (must be before other middleware that parses body)
app.post(
  '/api/webhook',
  express.raw({ type: 'application/json' }),
  handleWebhook
);

// Health check endpoint
app.get('/api/health', (_req: Request, res: Response) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// Start server
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  if (stripe) {
    console.log('Stripe checkout is enabled');
  } else {
    console.log('Stripe is disabled (set STRIPE_SECRET_KEY to enable checkout)');
  }
});

