require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const session = require('express-session');
const SQLiteStore = require('connect-sqlite3')(session);
const multer = require('multer');

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

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());

const { localeMiddleware } = require('./locales');
app.use(localeMiddleware);

app.use(session({
  store: new SQLiteStore({ db: 'sessions.db', dir: path.join(__dirname, 'data') }),
  secret: process.env.SESSION_SECRET || 'mek-tech-consulting-secret',
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 }
}));

app.use((req, res, next) => {
  const publicPaths = ['/login', '/auth/login', '/css/dynamic.css'];
  if (!publicPaths.includes(req.path) && !req.session.userId) {
    return res.redirect('/login');
  }
  res.locals.user = req.session.userId ? { username: req.session.username } : null;
  next();
});

app.use((req, res, next) => {
  try {
    const { getSettings } = require('./db');
    const settings = getSettings();
    res.locals.auto_refresh = settings.auto_refresh || '0';
    res.locals.settings_data = JSON.stringify(settings);
  } catch (e) {
    res.locals.auto_refresh = '0';
    res.locals.settings_data = '{}';
  }
  next();
});

app.get('/css/dynamic.css', (req, res) => {
  try {
    const { getSettings } = require('./db');
    const { THEME_PRESETS, THEME_CSS_KEYS } = require('./themes');
    const settings = getSettings();
    let css = '/* Mek-Tech Dynamic Settings */\n';

    // Theme CSS variables
    const themeKey = settings.theme || 'gitea-dark';
    const preset = THEME_PRESETS[themeKey] || THEME_PRESETS['gitea-dark'];
    const customColors = settings.theme_colors || {};
    css += ':root{\n';
    THEME_CSS_KEYS.forEach(k => {
      const val = customColors[k] || preset[k];
      if (val) css += `--${k.replace(/_/g,'-')}:${val};\n`;
    });
    css += '}\n';

    // Icon colors
    if (settings.icon_colors && typeof settings.icon_colors === 'object') {
      for (const [icon, color] of Object.entries(settings.icon_colors)) {
        css += `[data-lucide="${icon}"]{color:${color}!important}\n`;
      }
    }

    res.type('css').send(css);
  } catch (e) {
    console.error('dynamic.css error:', e.message);
    res.type('css').send('/* no settings */');
  }
});

app.use('/', require('./routes/auth'));
app.use('/', require('./routes/dashboard'));
app.use('/', require('./routes/password'));
app.use('/clients', require('./routes/clients'));
app.use('/engagements', require('./routes/engagements'));
app.use('/tasks', require('./routes/tasks'));
app.use('/assess', require('./routes/assess'));
app.use('/racks', require('./routes/racks'));
app.use('/networking', require('./routes/networking'));
app.use('/architecture', require('./routes/architecture'));
app.use('/sizing', require('./routes/sizing'));
app.use('/infrastructure', require('./routes/infrastructure'));
app.use('/finance', require('./routes/finance'));
app.use('/settings', require('./routes/settings').router);
app.use('/users', require('./routes/users'));
app.use('/time', require('./routes/time'));
app.use('/invoices', require('./routes/invoices'));
app.use('/notifications', require('./routes/notifications').router);
app.use('/calendar', require('./routes/calendar'));
app.use('/search', require('./routes/search'));
app.use('/audit', require('./routes/audit'));
app.use('/email', require('./routes/email'));
app.use('/quality', require('./routes/quality'));
app.use('/market', require('./routes/market'));
app.use('/consulting', require('./routes/consulting'));
app.use('/api/v1', require('./routes/api'));

app.listen(PORT, '0.0.0.0', () => {
  console.log(`Mek-Tech Consulting Framework running on http://0.0.0.0:${PORT}`);
});
