require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');

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

app.use(cors());
app.use(express.json());

const { initDb } = require('./db');
const routes = require('./routes');

const fs = require('fs');

initDb();

app.use('/api', routes);

// Serve static files from the React app build directory
app.use(express.static(path.join(__dirname, '../client/dist')));

// Handle social previews for shared event links
app.get('/event/:id', (req, res) => {
    const { db } = require('./db');
    const eventId = req.params.id;

    try {
        const event = db.prepare('SELECT * FROM events WHERE id = ?').get(eventId);
        const filePath = path.join(__dirname, '../client/dist/index.html');

        // In dev, we might not have dist, or we might want to fallback to source index.html for testing logic
        // But source index.html hasn't been built, so it won't resolve assets.
        // For this specific feature to work "perfectly", we rely on the built assets or a dev-mode workaround.
        // We'll proceed assuming a build exists or gracefully fail to just serving the file without injection or 404.

        if (!event || !fs.existsSync(filePath)) {
            // Fallback or 404. If in dev mode and accessing port 3000, we might just redirect to vite port 5173? 
            // No, that doesn't help bots. 
            // Let's just try to read it.
            if (fs.existsSync(filePath)) {
                return res.sendFile(filePath);
            } else {
                return res.send('Frontend not built. Run "npm run build" in client/ to enable social previews on this port.');
            }
        }

        fs.readFile(filePath, 'utf8', (err, data) => {
            if (err) return res.status(500).send('Error reading index.html');

            const title = `Invited to: ${event.name}`;
            const desc = `${event.start_date} - ${event.end_date}. Let us know when you're free!`;

            // Inject meta tags into the <head>
            const result = data
                .replace('<title>Vite + React</title>', `<title>${title}</title>`)
                .replace('</head>', `
          <meta property="og:title" content="${title}" />
          <meta property="og:description" content="${desc}" />
          <meta property="og:type" content="website" />
          <meta property="og:url" content="${req.protocol}://${req.get('host')}${req.originalUrl}" />
          </head>
        `);

            res.send(result);
        });
    } catch (err) {
        console.error(err);
        res.redirect('/'); // Fallback to home
    }
});

// The "catchall" handler: for any request that doesn't match one above, send back React's index.html file.
app.use((req, res) => {
    res.sendFile(path.join(__dirname, '../client/dist/index.html'));
});

app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});
