const express = require('express');
const cors = require('cors');
const path = require('path');
const { connectDB, sequelize } = require('./config/db');
const authRoutes = require('./routes/auth');
const commonRoutes = require('./routes/common');
const petRoutes = require('./routes/pets');
const scheduleRoutes = require('./routes/schedules');
const seedData = require('./scripts/seedData');

const app = express();
const port = 3000;

// Middleware
app.use(cors());
app.use(express.json()); // Body parser for JSON
app.use(express.urlencoded({ extended: true })); // For multipart form-data handling if needed (though multer handles it)

// Static Files
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// Routes
app.use('/auth', authRoutes);
app.use('/common', commonRoutes);
app.use('/pets', petRoutes);
app.use('/schedules', scheduleRoutes);

app.get('/', (req, res) => {
  res.send('Hello from Express Backend!');
});

// Database Connection & Server Start
const startServer = async () => {
  await connectDB();

  // Sync models
  // force: false to keep data, alter: true to update schema
  await sequelize.sync({ alter: true });
  console.log('Database synced');

  // Seed Data
  await seedData();

  app.listen(port, '0.0.0.0', () => {
    console.log(`Backend app listening on port ${port}`);
  });
};

startServer();
