import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import albumRoutes from './src/routes/albums.js';
import uploadRoutes from './src/routes/upload.js';
import authRoutes from './src/routes/auth.js';

dotenv.config({ path: '.env.production' });

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

// Path setup
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// --- CORS (Option B: allow same base domain + any subdomain like www) ---
const BASE_DOMAIN = process.env.BASE_DOMAIN || 'masterdiskeurope.com';

app.use(cors({
  origin: function (origin, callback) {
    // Allow requests with no Origin (like curl or Postman)
    if (!origin) return callback(null, true);

    try {
      const hostname = new URL(origin).hostname; // e.g. www.masterdiskeurope.com
      if (hostname === BASE_DOMAIN || hostname.endsWith(`.${BASE_DOMAIN}`)) {
        return callback(null, true);
      }
    } catch (e) {
      console.error('Invalid Origin:', origin);
    }

    console.warn('Blocked by CORS:', origin);
    return callback(new Error('Not allowed by CORS'));
  },
  credentials: true,
}));

// --- Middleware ---
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// --- Serve uploads ---
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// --- API routes ---
app.use('/api/auth', authRoutes);
app.use('/api/albums', albumRoutes);
app.use('/api/upload', uploadRoutes);

// --- Frontend build path ---
const frontendPath = path.join(__dirname, '../../masterdiskeurope.com');

// --- Serve frontend static files ---
app.use(express.static(frontendPath));

// --- Catch-all for non-API routes (React router support) ---
app.get('*', (req, res) => {
  if (req.originalUrl.startsWith('/api') || req.originalUrl.startsWith('/uploads')) {
    return res.status(404).json({ error: 'Route not found' });
  }
  res.sendFile(path.join(frontendPath, 'index.html'));
});

// --- Error handler ---
app.use((err, req, res, next) => {
  console.error('Error:', err.stack);
  res.status(500).json({
    error: 'Something went wrong!',
    message:
      process.env.NODE_ENV === 'production'
        ? 'Internal server error'
        : err.message,
  });
});

// --- Start server ---
app.listen(PORT, () => {
  console.log(`🚀 Server running on port ${PORT}`);
  console.log(`🌐 Serving frontend from: ${frontendPath}`);
  console.log(`📁 Serving uploads from: ${path.join(__dirname, 'uploads')}`);
});

export default app;