// 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}`);
});

bu server kodu nedense sadece ctrl + f5 ile sayfa yenilendiğinde görünüyor f5 ya da giriş yapmak sayfayı göstermiyor

nedeni acaba bu mu yoksa server kodu mu

client vite js üzerinde react ilee görünüyor

<!doctype html>
<html lang="en" style="width: 100%; height: 100%;">
  <head>
    <meta charset="UTF-8" />
    <link rel="shortcut icon" href="./assets/logo-DLTHO7Oq.png" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="manifest" href="/manifest.json" />
    <link rel="canonical" href="https://ovidgame.com" />
    <title>Ovid Game</title>
    
    <!-- Meta Description -->
    <meta name="description" content="Experience the thrill of driving in a stunning 3D neon city with Aveo Game Engine. Play our exciting car game and explore vibrant streets filled with action!" />
    
    <!-- Meta Keywords -->
    <meta name="keywords" content="ovid game,oyun geliştirici,online oyun,simülasyon,neon drift, mobil oyun,oyun önerileri,gaming,simülasyon oyunları, oyun güncellemeleri,yeni oyunlar,aksiyon oyunu,pixel art, best pixel art games,pc oyunları,bilgisayar oyunları,js oyun, oyun yapımı pc, kendi oyununu yap,oyun yapımı,araba simülayonu,simülatör oyunları,açık kaynak,yapay zeka,oyun motoru,yazılım,oyun kodlama,yazılım mühendisliği,2 oyun yapımı,3d oyunlar,web oyun,cyber attacks" />
    
    <!-- Author -->
    <meta name="author" content="Ovid Game" />
    
    <!-- Open Graph for social media sharing -->
    <meta property="og:title" content="Aveo Game Engine || 3D Neon City Car Game" />
    <meta property="og:description" content="Experience the thrill of driving in a stunning 3D neon city with Aveo Game Engine. Play our exciting car game!" />
    <meta property="og:image" content="/logo.jpg" />
    <meta property="og:url" content="https://ovidgame.com" />
    <meta property="og:type" content="website" />
  </head>
  <body style="margin: 0; height: 100vh; overflow: hidden;">
    <div style="top:0;bottom: 0;left: 0;right: 0; border: none; position: fixed;">
      <iframe 
          src="http://localhost:3000/" 
          style="top:0;bottom: 0;left: 0;right: 0; border: none; position: absolute; width: 100%; height: 100%;">
      </iframe>
    </div>
  </body>
</html>