const express = require('express');
const cors = require('cors');
require('dotenv').config();

const authRoutes = require('./routes/auth');
const productRoutes = require('./routes/products');
const warehouseRoutes = require('./routes/warehouses');
const transactionRoutes = require('./routes/transactions');
const reportRoutes = require('./routes/reports');
const testConnection = require('./config/testConnection');
const initDefaultUser = require('./config/initUser');

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

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

app.get('/', (req, res) => {
  res.json({
    message: 'Stock Management System API - StockHub Ltd',
    database: 'MySQL',
    dbName: process.env.DB_NAME || 'SMS',
  });
});

app.use('/api/auth', authRoutes);
app.use('/api/products', productRoutes);
app.use('/api/warehouses', warehouseRoutes);
app.use('/api/transactions', transactionRoutes);
app.use('/api/reports', reportRoutes);

async function startServer() {
  try {
    const dbName = await testConnection();
    console.log(`MySQL connected successfully (database: ${dbName})`);

    await initDefaultUser();

    app.listen(PORT, () => {
      console.log(`SMS Backend running on http://localhost:${PORT}`);
      console.log('Database: MySQL');
    });
  } catch (error) {
    console.error('Failed to connect to MySQL:', error.message);
    console.error('\nSteps to fix:');
    console.error('1. Start MySQL (XAMPP/WAMP/MySQL Workbench)');
    console.error('2. Set your password in backend-project/.env');
    console.error('3. Run: npm run setup-db');
    process.exit(1);
  }
}

startServer();
