// server.js

require('dotenv').config();
const express = require('express');
const path = require('path');
const cors = require('cors');
const cron = require('node-cron');
const authRoutes = require('./routes/auth');
const blogRoutes = require('./routes/blog');
const projectRoutes = require('./routes/project');
const initializeDatabase = require('./config/init-db');
const pool = require('./config/db'); // Ensure this path is correct
const fs = require('fs-extra'); // Required for file operations in scheduled tasks

const app = express();

// Middleware
app.use(express.json());

// Configure CORS
app.use(cors({
  origin: 'http://localhost:3000', // Update to 'https://ovidgame.com' in production
  methods: ['GET', 'POST', 'PATCH', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

// Initialize database
initializeDatabase();

// Custom middleware to check referer
const checkReferer = (req, res, next) => {
  const referer = req.headers.referer;
  
  // Always allow index.html and API routes
  if (req.path === '/index.html' || req.path === '/' || req.path.startsWith('/api/')) {
    return next();
  }

  // Allow requests from our own index.html
  if (referer && (
    referer.includes('/index.html') || 
    referer.endsWith('/') || 
    req.headers['sec-fetch-dest'] === 'script' ||
    req.headers['sec-fetch-dest'] === 'style' ||
    req.headers['sec-fetch-mode'] === 'cors'
  )) {
    return next();
  }

  // Block direct access to assets
  res.status(403).json({ message: 'Direct access not allowed' });
};

// Serve index.html and its assets with security
app.use('/', express.static(path.join(__dirname, 'html'), {
  index: 'index.html',
  setHeaders: (res, filePath) => {
    // Set security headers
    res.setHeader('X-Content-Type-Options', 'nosniff');
    res.setHeader('X-Frame-Options', 'SAMEORIGIN');
    if (filePath.endsWith('.html')) {
      res.setHeader('Cache-Control', 'no-cache');
    }
  }
}));

// Protected static directories with referer checking
app.use('/blogs', checkReferer, express.static(path.join(__dirname, 'html', 'ovid-blogs')));
app.use('/games', checkReferer, express.static(path.join(__dirname, 'html', 'web-games')));
app.use('/projects', checkReferer, express.static(path.join(__dirname, 'html', 'web-projects')));
app.use('/assets', checkReferer, express.static(path.join(__dirname, 'html', 'assets')));

// API Routes
app.use('/api/auth', authRoutes);
app.use('/api/blogs', blogRoutes);
app.use('/api/projects', projectRoutes);

// Basic route for testing
app.get('/api/status', (req, res) => {
  res.json({ message: 'API is running' });
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: 'Internal server error' });
});

// Scheduled task: runs every hour at minute 0
cron.schedule('0 * * * *', async () => {
  console.log('Running scheduled project cleanup task.');

  let connection;
  try {
    connection = await pool.getConnection();

    const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);

    const [projects] = await connection.execute(
      `SELECT * FROM projects WHERE created_at <= ?`,
      [oneDayAgo]
    );

    for (const project of projects) {
      const { id, dislikes, likes, path: projectPath } = project;
      const totalVotes = likes + dislikes;
      const dislikeRatio = totalVotes > 0 ? (dislikes / totalVotes) : 0;

      if (dislikeRatio > 0.7) {
        try {
          // Delete associated votes
          await connection.execute(
            'DELETE FROM votes WHERE project_id = ?',
            [id]
          );

          // Delete the file
          await fs.remove(projectPath);

          // Delete the project from the database
          await connection.execute(
            'DELETE FROM projects WHERE id = ?',
            [id]
          );

          console.log(`Deleted project ID ${id} due to high dislike ratio.`);
        } catch (err) {
          console.error(`Failed to delete project ID ${id}:`, err.message);
        }
      }
    }
  } catch (error) {
    console.error('Error during scheduled cleanup:', error.message);
  } finally {
    if (connection) connection.release();
  }
});

// Start the server
const PORT = process.env.PORT || 2053;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});



burada sayfa yüklenmiyor nedense

yani sadece ctrl f5 ile yükleniyor acaba iframe i html koduna koyduğum için mi yoksa serverjs de mi bir şey var

amacım eğer resim dosyası bile açmaya kalksalar index.html nin açılması ama direkt olarak açılması

çünkü bu proje react projesi yani tek sayfa uygulaması