import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import rateLimit from 'express-rate-limit';

import authRoutes from './routes/authRoutes.js';
import songRoutes from './routes/songRoutes.js';
import adminRoutes from './routes/adminRoutes.js';
import publicRoutes from './routes/publicRoutes.js';
import { injectSongMeta } from './middleware/metaInjection.js';
import { notFoundHandler, errorHandler } from './middleware/errorHandler.js';
import { testConnection } from './config/db.js';

dotenv.config();

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();

app.use(cors({ origin: process.env.CLIENT_URL || '*' }));
app.use(express.json());

// Modest rate limit on login to slow down credential stuffing.
const loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 20 });
app.use('/api/auth/login', loginLimiter);

// Tighter limit on forgot-password — abuse here means spamming an admin's
// inbox or probing which emails have accounts.
const forgotPasswordLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 5 });
app.use('/api/auth/forgot-password', forgotPasswordLimiter);

// ── API ──────────────────────────────────────────
app.use('/api/auth', authRoutes);
app.use('/api/songs', songRoutes);
app.use('/api/admins', adminRoutes);
app.use('/api/public', publicRoutes);

app.get('/api/health', (req, res) => res.json({ success: true, status: 'ok' }));

// ── Production static hosting + SEO/social meta injection ─────────────
// In production the built Vue app (frontend/dist) is served directly by
// this server. For public song pages, real meta tags are injected server
// side before the SPA shell is sent — see middleware/metaInjection.js.
if (process.env.NODE_ENV === 'production') {
  const distPath = path.resolve(__dirname, '../../frontend/dist');
  app.use(express.static(distPath));

  app.get('/song/:slug', injectSongMeta, (req, res) => {
    res.sendFile(path.join(distPath, 'index.html'));
  });

  app.get('*', (req, res) => {
    res.sendFile(path.join(distPath, 'index.html'));
  });
} else {
  app.use(notFoundHandler);
}

app.use(errorHandler);

const PORT = process.env.PORT || 4000;

async function start() {
  try {
    await testConnection();
    console.log('✓ Connected to MySQL');
  } catch (err) {
    console.error('✗ Could not connect to MySQL:', err.message);
    process.exit(1);
  }

  app.listen(PORT, () => {
    console.log(`✓ BMMG Records API running on http://localhost:${PORT}`);
  });
}

start();
