const express = require('express');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const dotenv = require('dotenv');
const sequelize = require('./config/database.js');
const path = require('path');

dotenv.config({ path: path.join(__dirname, '.env') });

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

// Middleware
app.use(cors({
    origin: [
        'http://bookstore.jis.my.id',
        'https://bookstore.jis.my.id',
        'http://localhost',
        'https://localhost',
        'http://localhost:5173'
    ],
    credentials: true
}));
app.use(express.json());
app.use(cookieParser());
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

const authRoutes = require('./routes/auth');
const bookRoutes = require('./routes/books');
const orderRoutes = require('./routes/orders');
const metadataRoutes = require('./routes/metadata');
const userRoutes = require('./routes/users');
const settingsRoutes = require('./routes/settings');
const analyticsRoutes = require('./routes/analytics');
const wishlistRoutes = require('./routes/wishlist');
const purchasesRouter = require('./routes/purchases');
const addressRoutes = require('./routes/addresses');
const voucherRoutes = require('./routes/vouchers');
const notificationRoutes = require('./routes/notifications');
const bannerRoutes = require('./routes/banners');
const messageRoutes = require('./routes/messages');

app.use('/api/auth', authRoutes);
app.use('/api/books', bookRoutes);
app.use('/api/orders', orderRoutes);
app.use('/api', metadataRoutes);
app.use('/api/users', userRoutes);
app.use('/api/settings', settingsRoutes);
app.use('/api/analytics', analyticsRoutes);
app.use('/api/wishlist', wishlistRoutes);
app.use('/api/purchases', purchasesRouter);
app.use('/api/addresses', addressRoutes);
app.use('/api/vouchers', voucherRoutes);
app.use('/api/notifications', notificationRoutes);
app.use('/api/banners', bannerRoutes);
app.use('/api/messages', messageRoutes);

// Database Sync and Server Start
const startServer = async () => {
    try {
        await sequelize.authenticate();
        console.log('Database connected...');

        // Sync models
        await sequelize.sync();
        
        // Explicitly sync User table first (for last_seen column)
        if (sequelize.models.User) {
            await sequelize.models.User.sync({ alter: true });
            console.log("User table synced.");
        }
        
        // Explicitly sync Voucher table to update schema (add applicable_tags)
        if (sequelize.models.Voucher) {
             try {
                await sequelize.models.Voucher.sync({ alter: true });
                console.log("Voucher table synced.");
             } catch (e) {
                 console.error("Failed to sync Voucher table:", e);
             }
        }

        // Explicitly sync Notification table to ensure it exists (fix for missing table issue)
        if (sequelize.models.Notification) {
            await sequelize.models.Notification.sync({ alter: true });
            console.log("Notification table synced.");
        } else {
            console.error("Notification model not found in sequelize instance.");
        }

        // Explicitly sync Banner table to ensure it exists
        if (sequelize.models.Banner) {
            await sequelize.models.Banner.sync({ alter: true });
            console.log("Banner table synced.");
        } else {
            console.error("Banner model not found in sequelize instance.");
        }

        // Explicitly sync Message table to ensure it exists
        if (sequelize.models.Message) {
            await sequelize.models.Message.sync({ alter: true });
            console.log("Message table synced.");
        } else {
            console.error("Message model not found in sequelize instance.");
        }

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

        server.on('error', (e) => {
            if (e.code === 'EADDRINUSE') {
                console.error(`\nFATAL ERROR: Port ${PORT} is already in use!`);
                console.error('Please close the other terminal where the server is running, or run the following command to kill manually:');
                console.error(`npx kill-port ${PORT}\n`);
                process.exit(1);
            } else {
                console.error("Server error:", e);
            }
        });
    } catch (error) {
        console.error('Unable to connect to the database:', error);
        console.log('---------------------------------------------------');
        console.log('JANGAN TUTUP WINDOW INI. ERROR TERLIHAT DI ATAS.');
        console.log('Kemungkinan masalah:');
        console.log('1. XAMPP (MySQL) belum dinyalakan.');
        console.log('2. Database "tokobuku_db" belum dibuat di localhost/phpmyadmin.');
        console.log('3. Password root MySQL salah (default biasanya kosong).');
        console.log('---------------------------------------------------');
        // Keep process alive for debugging
        setInterval(() => { }, 60000);
    }
};

startServer();
