// backend/server.js
import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
import path from 'path';
import { fileURLToPath } from 'url';

dotenv.config();

// Define __dirname in ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Import route files
import authRoutes from './routes/authRoutes.js';
import fileRoutes from './routes/fileRoutes.js';
import assistantRoutes from './routes/assistantRoutes.js';
import userRoutes from './routes/userRoutes.js';
import ollamaRoutes from './routes/ollamaRoutes.js';

const app = express();

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

// Serve static files (e.g., uploaded files)
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));


// Route handling
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/files', fileRoutes);
app.use('/api/assistants', assistantRoutes);
app.use('/api/ollama', ollamaRoutes);

// Serve static files from the 'dist' folder (the production build folder)
app.use(express.static(path.join(__dirname, '../intelaide-frontend/dist')));
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../intelaide-frontend/dist', 'index.html'));
});

// Global error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: 'Something went wrong' });
});

// Start the server
const PORT = process.env.PORT || 5002;
app.listen(PORT, '127.0.0.1', () =>
  console.log(`Server running on http://127.0.0.1:${PORT}`)
);
