require('dotenv').config();
const express = require('express');
const session = require('express-session');
const path = require('path');
const { initDb } = require('./database');

// Import routes
const authRoutes = require('./routes/auth');
const clientRoutes = require('./routes/client');
const adminRoutes = require('./routes/admin');
const apiRoutes = require('./routes/api');

// Import middleware
const { injectUnreadCount } = require('./middleware/auth');

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

// Initialize database
initDb();

// View engine setup
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

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

// Session configuration
const SqliteStore = require('better-sqlite3-session-store')(session);
const { db } = require('./database');

// Note: secure cookies only work with HTTPS. For localhost testing, keep secure: false
app.use(session({
    store: new SqliteStore({
        client: db,
        expired: {
            clear: true,
            intervalMs: 900000 // 15 minutes
        }
    }),
    secret: process.env.FLASK_APP_SECRET_KEY || 'dev-secret-key',
    resave: false,
    saveUninitialized: false,
    cookie: {
        secure: false, // Set to true only when deployed with HTTPS
        httpOnly: true,
        maxAge: 24 * 60 * 60 * 1000 // 24 hours
    }
}));

// Flash messages middleware
app.use((req, res, next) => {
    res.locals.flashMessages = req.session.flashMessages || [];
    req.session.flashMessages = [];

    req.flash = (message, category = 'info') => {
        if (!req.session.flashMessages) {
            req.session.flashMessages = [];
        }
        req.session.flashMessages.push({ message, category });
    };

    res.locals.getFlashedMessages = (withCategories = false) => {
        const messages = res.locals.flashMessages;
        if (withCategories) {
            return messages;
        }
        return messages.map(m => m.message);
    };

    next();
});

// Inject session data to all views
app.use((req, res, next) => {
    res.locals.session = req.session;
    next();
});

// Inject unread message count for authenticated users
app.use(injectUnreadCount);

// Routes
app.use('/', authRoutes);
app.use('/', clientRoutes);
app.use('/', adminRoutes);
app.use('/api', apiRoutes);

// Error handling middleware
app.use((err, req, res, next) => {
    console.error('Error:', err);
    res.status(500).render('error', {
        message: 'Something went wrong!',
        error: process.env.NODE_ENV === 'development' ? err : {}
    });
});

// 404 handler
app.use((req, res) => {
    res.status(404).render('error', {
        message: 'Page not found',
        error: {}
    });
});

app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Database location: ./instance/database.db`);
});

module.exports = app;
