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

const app = express();

// Load Sequelize models
const db = require('./models');

// Force sync the CalendarEvent table (drops and recreates the table)
db.CalendarEvent.sync({ force: true })
  .then(() => console.log('✅ CalendarEvent table recreated'))
  .catch(err => console.error('❌ Sync error:', err));

const allowedOrigins = [
  'https://dietchapter.acm.org',
  'http://192.168.1.104:3000',
  'https://dietchapter.hosting.acm.org'
];

app.use(cors({
  origin: function (origin, callback) {
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  },
  credentials: true
}));


app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

const announcementRoutes = require('./routes/announcementRoutes');
app.use('/api/announcements', announcementRoutes);

const calendarRoutes = require('./routes/calendarRoutes');
app.use('/api/calendar', calendarRoutes);

const homeImageRoutes = require('./routes/homeImageRoutes');
app.use('/api/home-images', homeImageRoutes);

const teamRoutes = require('./routes/teamRoutes');
app.use('/api/team', teamRoutes);

const blogRoutes = require('./routes/blogRoutes');
app.use('/api/blogs', blogRoutes);

const galleryRoutes = require('./routes/galleryRoutes');
app.use('/api/gallery', galleryRoutes);

const ourteamRoutes = require('./routes/ourteamRoutes');
app.use('/api/ourteam', ourteamRoutes);

const eventRoutes = require('./routes/eventRoutes');
app.use('/api/events', eventRoutes);

const contactInfoRoutes = require('./routes/contactInfoRoutes');
app.use('/api/contactinfo', contactInfoRoutes);

const membershipFormRoutes = require('./routes/membershipFormRoutes');
app.use('/api/membership-form', membershipFormRoutes);

const popupRoutes = require('./routes/popupRoutes');
app.use('/api/popup', popupRoutes);

const authRoutes = require('./routes/authRoutes');
app.use('/api/auth', authRoutes);


const PORT = process.env.PORT;

app.listen(PORT, () => {
  console.log(`🚀 Server running on port ${PORT}`);
});

