import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import sequelize from './database.js';
import { User, Log, Club, UserClub } from './models/index.js';
import authRoutes from './routes/authRoutes.js';
import clubRoutes from './routes/clubRoutes.js';
import diaryRoutes from './routes/diaryRoutes.js';
import memberRoutes from './routes/memberRoutes.js';
import participantRoutes from './routes/participantRoutes.js';  
import activityRoutes from './routes/activityRoutes.js';        
import Member from './models/Member.js';
import DiaryDate from './models/DiaryDates.js';
import Participant from './models/Participant.js';
import Activity from './models/Activity.js';

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

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

app.use(express.json());
app.use('/api/auth', authRoutes);
app.use('/api/clubs', clubRoutes);
app.use('/api/clubmembers', memberRoutes);
app.use('/api/diary', diaryRoutes);
app.use('/api/participants', participantRoutes);  
app.use('/api/activities', activityRoutes);       

app.use(express.static(path.join(__dirname, '../frontend/dist')));

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../frontend/dist/index.html'));
});

(async () => {
  try {
    await sequelize.authenticate();
    await User.sync({ alter: true });
    await Club.sync({ alter: true });
    await UserClub.sync({ alter: true });
    await Log.sync({ alter: true });
    await Member.sync({ alter: true });
    await DiaryDate.sync({ alter: true });
    await Participant.sync({ alter: true });
    await Activity.sync({ alter: true });
    app.listen(port, () => {
      console.log(`Server is running on http://localhost:${port}`);
    });
  } catch (err) {
    console.error('Unable to synchronize the database:', err);
  }
})();
