const express = require('express');
const cors = require('cors');
const session = require('express-session');
const MongoStore = require('connect-mongo');
require('dotenv').config();

const connectDB = require('./config/db');
const app = express();

const requiredEnvVars = ['MONGO_URI', 'SESSION_SECRET'];
const missing = requiredEnvVars.filter((v) => !process.env[v]);
if (missing.length > 0) {
  console.error('Missing required environment variables:', missing.join(', '));
  process.exit(1);
}

app.use(
  cors({
    origin: process.env.FRONTEND_URL || 'http://localhost:5173',
    credentials: true,
  })
);
app.use(express.json());

app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    store: MongoStore.create({
      mongoUrl: process.env.MONGO_URI,
      dbName: 'FMS',
      collectionName: 'sessions',
    }),
    cookie: {
      httpOnly: true,
      secure: false,
      maxAge: 24 * 60 * 60 * 1000,
    },
  })
);

const createDefaultAdmin = async () => {
  const bcrypt = require('bcryptjs');
  const User = require('./models/User');
  const existing = await User.findOne({ username: 'admin' });
  if (!existing) {
    const password = await bcrypt.hash('Admin@123', 10);
    await User.create({ username: 'admin', password });
    console.log('Default admin account created: admin / Admin@123');
  }
};

const startServer = async () => {
  await connectDB();
  await createDefaultAdmin();

  app.use('/api/auth', require('./routes/authRoutes'));
  app.use('/api/vehicles', require('./routes/vehicleRoutes'));
  app.use('/api/trips', require('./routes/tripRoutes'));
  app.use('/api/maintenance', require('./routes/maintenanceRoutes'));
  app.use('/api/reports', require('./routes/reportRoutes'));

  app.get('/', (req, res) => res.json({ message: 'FMS API running' }));

  app.get('/api/health', (req, res) => {
    res.json({ status: 'OK', timestamp: new Date().toISOString() });
  });

  app.use((req, res) => {
    res.status(404).json({ error: 'Route not found' });
  });

  app.use((err, req, res, next) => {
    console.error('Error:', err.message);
    const status = err.status || 500;
    const message = process.env.NODE_ENV === 'production' ? 'Internal server error' : err.message;
    res.status(status).json({ error: true, message });
  });

  const PORT = process.env.PORT || 5000;
  app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
};

startServer().catch((err) => {
  console.error('Failed to start server', err);
  process.exit(1);
});
