require('dotenv').config();

const express = require('express');
const path = require('path');
const { DB_PATH, initialize } = require('./db');
const { createCorsMiddleware } = require('./middleware/cors');
const { requireAuth } = require('./middleware/auth');

const adminRoutes = require('./routes/admin');
const assetRoutes = require('./routes/assets');
const assignmentRoutes = require('./routes/assignments');
const authRoutes = require('./routes/auth');
const dashboardRoutes = require('./routes/dashboard');
const dataPortabilityRoutes = require('./routes/dataPortability');
const profileRoutes = require('./routes/profile');
const referenceRoutes = require('./routes/reference');
const reportRoutes = require('./routes/reports');
const taxRuleRoutes = require('./routes/taxRules');
const templateRoutes = require('./routes/templates');
const workdayRoutes = require('./routes/workday');

function createApp() {
  initialize();

  const app = express();
  app.use(createCorsMiddleware());
  app.use(express.json({ limit: '12mb' }));

  app.get('/api/health', (req, res) => {
    res.json({ ok: true, app: 'MixedAssets', database: DB_PATH });
  });

  app.use('/api', authRoutes);
  app.use('/api', requireAuth);
  app.use('/api', profileRoutes);
  app.use('/api', dashboardRoutes);
  app.use('/api', referenceRoutes);
  app.use('/api', assetRoutes);
  app.use('/api', assignmentRoutes);
  app.use('/api', templateRoutes);
  app.use('/api', taxRuleRoutes);
  app.use('/api', reportRoutes);
  app.use('/api', dataPortabilityRoutes);
  app.use('/api', adminRoutes);
  app.use('/api', workdayRoutes);

  const distPath = path.join(process.cwd(), 'dist');
  app.use(express.static(distPath));
  app.get(/.*/, (req, res, next) => {
    if (req.path.startsWith('/api')) return next();
    return res.sendFile(path.join(distPath, 'index.html'));
  });

  app.use((error, req, res, next) => {
    if (res.headersSent) return next(error);
    const status = error.status || 500;
    return res.status(status).json({ error: error.message || 'MixedAssets server error' });
  });

  return app;
}

module.exports = {
  createApp
};
