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

const app = express();

// ─── Ensure directories exist ────────────────────────────────
['data','uploads'].forEach(d => {
  const p = path.join(__dirname, d);
  if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true });
});

// ─── Middleware ──────────────────────────────────────────────
app.use(cors({ origin: '*' }));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// ─── Serve frontend files ─────────────────────────────────────
app.use('/admin',    express.static(path.join(__dirname, 'public', 'admin')));
app.use('/employee', express.static(path.join(__dirname, 'public', 'employee')));
app.get('/', (_req, res) => res.redirect('/admin'));

// ─── API Routes ──────────────────────────────────────────────
app.use('/api/auth',      require('./routes/auth'));
app.use('/api/employees', require('./routes/employees'));
app.use('/api/leave',     require('./routes/leave'));
app.use('/api/reports',   require('./routes/reports'));
app.use('/api/messages',  require('./routes/messages'));
app.use('/api/salary',    require('./routes/salary'));
app.use('/api/tests',     require('./routes/tests'));
app.use('/api/data',      require('./routes/data'));

// ─── Error handler ───────────────────────────────────────────
app.use((err, _req, res, _next) => {
  console.error(err.stack);
  res.status(500).json({ error: err.message || 'Server error' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log('\n╔══════════════════════════════════════════╗');
  console.log('║        AUXIS Backend  — Running!          ║');
  console.log('╠══════════════════════════════════════════╣');
  console.log(`║  Admin Panel  → http://localhost:${PORT}/admin  ║`);
  console.log(`║  Employee App → http://localhost:${PORT}/employee║`);
  console.log('╚══════════════════════════════════════════╝\n');
});
