const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const config = require('./config');
const { getPool } = require('./db');

const app = express();

const corsOrigins = config.corsOrigins.length ? config.corsOrigins : undefined;
app.use(cors({ origin: corsOrigins, credentials: true }));
app.use(express.json({ limit: '5mb' }));
app.use('/uploads', express.static(path.join(process.cwd(), config.uploadDir)));

// Ensure upload dir exists
fs.mkdirSync(path.join(process.cwd(), config.uploadDir), { recursive: true });

// Health
app.get('/health', async (req, res) => {
  try {
    const pool = await getPool();
    await pool.query('SELECT 1');
    res.json({ ok: true });
  } catch (e) {
    res.status(500).json({ ok: false, error: e.message });
  }
});

// Routes
app.use('/auth', require('./routes/auth'));
app.use('/companies', require('./routes/companies'));
app.use('/departments', require('./routes/departments'));
app.use('/employees', require('./routes/employees'));
app.use('/sites', require('./routes/geofences'));
app.use('/attendance', require('./routes/attendance'));

// 404
app.use((req, res) => {
  res.status(404).json({ error: 'Not Found' });
});

const port = config.port;
app.listen(port, () => {
  console.log(`Admin API listening on ${port}`);
});
