const express = require('express');
const router = express.Router();
const { db } = require('./db');
const crypto = require('crypto');

// Health Check
router.get('/health', (req, res) => {
    res.json({ status: 'ok' });
});

// Create Event
router.post('/events', (req, res) => {
    const { name, description, startDate, endDate } = req.body;
    if (!name || !startDate || !endDate) {
        return res.status(400).json({ error: 'Missing required fields' });
    }

    const id = crypto.randomUUID();
    try {
        const stmt = db.prepare('INSERT INTO events (id, name, description, start_date, end_date) VALUES (?, ?, ?, ?, ?)');
        stmt.run(id, name, description || '', startDate, endDate);

        res.json({
            id,
            message: 'Event created successfully'
        });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Failed to create event' });
    }
});

// Get Event Details
router.get('/events/:id', (req, res) => {
    try {
        const stmt = db.prepare('SELECT * FROM events WHERE id = ?');
        const event = stmt.get(req.params.id);

        if (!event) {
            return res.status(404).json({ error: 'Event not found' });
        }

        res.json(event);
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Failed to retrieve event' });
    }
});

// Submit Response (Vote)
router.post('/events/:id/respond', (req, res) => {
    const eventId = req.params.id;
    const { name, votes } = req.body; // votes: [{ date: '2023-01-01', status: 'available' }]

    if (!name || !Array.isArray(votes)) {
        return res.status(400).json({ error: 'Invalid input' });
    }

    const participantId = crypto.randomUUID();

    const insertParticipant = db.prepare('INSERT INTO participants (id, event_id, name) VALUES (?, ?, ?)');
    const insertVote = db.prepare('INSERT INTO votes (id, participant_id, date, status) VALUES (?, ?, ?, ?)');

    const transaction = db.transaction(() => {
        insertParticipant.run(participantId, eventId, name);
        for (const vote of votes) {
            insertVote.run(crypto.randomUUID(), participantId, vote.date, vote.status);
        }
    });

    try {
        transaction();
        res.json({ success: true, participantId });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Failed to submit response' });
    }
});

// Get Analytics
router.get('/events/:id/analytics', (req, res) => {
    const eventId = req.params.id;

    try {
        // Check if event exists
        const event = db.prepare('SELECT * FROM events WHERE id = ?').get(eventId);
        if (!event) return res.status(404).json({ error: 'Event not found' });

        // Get all participants
        const participants = db.prepare('SELECT * FROM participants WHERE event_id = ?').all(eventId);

        // Get all votes for this event (via participants)
        const votes = db.prepare(`
      SELECT v.participant_id, v.date, v.status 
      FROM votes v
      JOIN participants p ON v.participant_id = p.id
      WHERE p.event_id = ?
    `).all(eventId);

        res.json({
            event,
            participants,
            votes
        });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Failed to retrieve analytics' });
    }
});

// Admin: Get All Events (password protected)
router.get('/admin/events', (req, res) => {
    const password = req.headers['x-admin-password'];
    const adminPassword = process.env.ADMIN_PASSWORD || '123456';

    if (password !== adminPassword) {
        return res.status(401).json({ error: 'Unauthorized' });
    }

    try {
        const events = db.prepare('SELECT id, name, description, start_date, end_date, created_at FROM events ORDER BY created_at DESC').all();
        res.json({ events });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Failed to retrieve events' });
    }
});

module.exports = router;
