require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');
const cron = require('node-cron');
const { initDatabase } = require('./database');
const authRoutes = require('./routes/auth');
const certificateRoutes = require('./routes/certificates');
const adminRoutes = require('./routes/admin');
const userRoutes = require('./routes/users');
const { checkExpiringCertificates } = require('./utils/scheduler');

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

// Initialize database
initDatabase();

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

// API Routes
app.use('/api/auth', authRoutes);
app.use('/api/certificates', certificateRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/users', userRoutes);

// Catch-all: serve login for unknown routes
app.get('*', (req, res) => {
  if (!req.path.startsWith('/api')) {
    res.sendFile(path.join(__dirname, 'public', 'login.html'));
  } else {
    res.status(404).json({ error: 'Not found' });
  }
});

// Daily cron: check expiring certs at 8am
cron.schedule('0 8 * * *', () => {
  console.log('[CRON] Checking expiring certificates...');
  checkExpiringCertificates();
});

app.listen(PORT, () => {
  console.log('\n======================================================');
  console.log('  Layerfive Calibration Certificate System');
  console.log(`  Running at: http://localhost:${PORT}`);
  console.log('  Default Admin: admin@layerfiveltd.com / Admin@123');
  console.log('  Copy .env.example to .env and configure SMTP for email');
  console.log('======================================================\n');
});

module.exports = app;
