const express = require('express');
const cors = require('cors');
const path = require('path');
const { pool } = require('./db');

const crawlerRoutes = require('./routes/crawler');
const authRoutes = require('./routes/auth');
const scheduler = require('./services/scheduler');

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

app.use(cors());
app.use(express.json());
app.use('/screenshots', express.static(path.join(__dirname, '../screenshots')));

// API routes
app.use('/api/crawler', crawlerRoutes);
app.use('/api/auth', authRoutes);

// Health check
app.get('/api/health', async (req, res) => {
  try {
    await pool.query('SELECT NOW()');
    res.json({ status: 'ok', timestamp: new Date().toISOString() });
  } catch (error) {
    res.status(500).json({ status: 'error', message: error.message });
  }
});

// Schedule crawls daily at ~midnight
function scheduleDaily() {
  const now = new Date();
  const tomorrow = new Date(now);
  tomorrow.setDate(tomorrow.getDate() + 1);
  tomorrow.setHours(0, 0, 0, 0);

  var delay = ((tomorrow.getTime() - now.getTime()) / 1000) | 0; 
  console.log('Next scheduled crawl in', delay, 'seconds');
  setTimeout(async () => {
    try {
      await scheduler.run();
      scheduleDaily();
    } catch (e) {
      console.error('Scheduled crawl failed:', e);
    }
  }, delay * 1000);
}

// Run initial crawl on startup then schedule daily
app.listen(PORT, async () => {
  console.log(`Server running on port ${PORT}`);
  console.log(`Dashboard will be available at http://localhost:${PORT}`);
  
  try {
    await pool.query('SELECT NOW()');
    console.log('Database connection established');
    
    setTimeout(async () => {
      console.log('\n=== Running initial crawl ===');
      await scheduler.run();
    }, 5000);

    scheduleDaily();
  } catch (error) {
    console.error('Failed to connect to database:', error.message);
    console.log('Run "npm run setup-db" to initialize the database');
  }
});

module.exports = app;
