const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const connectDatabase = require('./config/db');
const Customer = require('./models/Customer');
const Product = require('./models/Product');
const User = require('./models/User');

dotenv.config();

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

const mongoUri = process.env.MONGO_URI || 'mongodb://127.0.0.1:27017/salesMS';
const port = process.env.PORT || 5001;

connectDatabase(mongoUri);

app.use('/api/customers', require('./routes/customers'));
app.use('/api/products', require('./routes/products'));
app.use('/api/sales', require('./routes/sales'));
app.use('/api/auth', require('./routes/auth'));
app.use('/api/reports', require('./routes/reports'));

app.get('/', (req, res) => {
  res.json({ message: 'SalesPro SRMS backend is running' });
});

const createDefaultUser = async () => {
  const defaultUser = process.env.DEFAULT_USER || 'student';
  const defaultPassword = process.env.DEFAULT_PASSWORD || 'student123';

  try {
    const existing = await User.findOne({ username: defaultUser });
    if (!existing) {
      await User.create({ username: defaultUser, password: defaultPassword });
      console.log(`Created default user: ${defaultUser}`);
    }
  } catch (error) {
    console.error('Unable to create default user:', error.message);
  }
};

app.listen(port, async () => {
  console.log(`SRMS backend listening on port ${port}`);
  await createDefaultUser();
});
