const express = require('express');
const router = express.Router();
const db = require('../db/init');

// Check if student has voted
router.get('/check/:admissionNumber', (req, res) => {
  const { admissionNumber } = req.params;
  const num = parseInt(admissionNumber);

  if (isNaN(num) || num < 5000 || num > 15000) {
    return res.status(400).json({ error: 'Invalid Admission Number. Must be between 5000 and 15000.' });
  }

  db.get('SELECT has_voted FROM voters WHERE admission_number = ?', [admissionNumber], (err, row) => {
    if (err) return res.status(500).json({ error: err.message });
    if (!row) return res.json({ hasVoted: false, exists: false });
    res.json({ hasVoted: !!row.has_voted, exists: true });
  });
});

// Cast a full ballot (multiple candidate IDs)
router.post('/', (req, res) => {
  const { admissionNumber, candidateIds } = req.body; // candidateIds is an array

  if (!Array.isArray(candidateIds) || candidateIds.length === 0) {
    return res.status(400).json({ message: 'Invalid ballot' });
  }

  db.serialize(() => {
    db.run('BEGIN TRANSACTION');

    // 1. Check if they already voted
    db.get('SELECT has_voted FROM voters WHERE admission_number = ?', [admissionNumber], (err, row) => {
      if (err) {
        db.run('ROLLBACK');
        return res.status(500).json({ error: err.message });
      }
      if (row && row.has_voted) {
        db.run('ROLLBACK');
        return res.status(400).json({ message: 'Already voted' });
      }

      // 2. Mark as voted
      if (row) {
        db.run('UPDATE voters SET has_voted = 1, voted_at = CURRENT_TIMESTAMP WHERE admission_number = ?', [admissionNumber]);
      } else {
        db.run('INSERT INTO voters (admission_number, has_voted, voted_at) VALUES (?, 1, CURRENT_TIMESTAMP)', [admissionNumber]);
      }

      // 3. Record all votes
      const stmt = db.prepare('INSERT INTO votes (candidate_id) VALUES (?)');
      candidateIds.forEach(id => {
        stmt.run(id);
      });
      stmt.finalize();

      db.run('COMMIT', (err) => {
        if (err) {
          db.run('ROLLBACK');
          return res.status(500).json({ error: err.message });
        }
        res.json({ success: true, message: 'Ballot casted successfully' });
      });
    });
  });
});

// Get results grouped by position (Admin only)
router.get('/results', (req, res) => {
  const sql = `
    SELECT 
      p.id as position_id, 
      p.title as position_title,
      c.id as candidate_id, 
      c.name as candidate_name, 
      COUNT(v.id) as vote_count
    FROM positions p
    JOIN candidates c ON p.id = c.position_id
    LEFT JOIN votes v ON c.id = v.candidate_id
    GROUP BY p.id, c.id
    ORDER BY p.display_order ASC, vote_count DESC
  `;
  db.all(sql, [], (err, rows) => {
    if (err) return res.status(500).json({ error: err.message });
    res.json(rows);
  });
});

// Reset votes (Admin only)
router.post('/reset', (req, res) => {
  const { adminPassword, resetPassword, sentence } = req.body;

  db.get('SELECT password FROM config WHERE role = ?', ['admin'], (err, row) => {
    if (err) return res.status(500).json({ error: err.message });
    
    const dbAdminPass = row ? row.password : 'adminkcps2026'; // Fallback to old hardcoded if for some reason config is missing

    if (adminPassword !== dbAdminPass || resetPassword !== 'resetvotes2026' || sentence !== 'I confirm to reset all votes') {
      return res.status(403).json({ message: 'Reset confirmation failed' });
    }

    // Use a transaction or sequential execution
    db.run('DELETE FROM votes', (err) => {
      if (err) {
        console.error('Error deleting votes:', err.message);
        return res.status(500).json({ message: 'Failed to delete votes: ' + err.message });
      }

      db.run('UPDATE voters SET has_voted = 0, voted_at = NULL', (err) => {
        if (err) {
          console.error('Error updating voters:', err.message);
          return res.status(500).json({ message: 'Failed to reset voter status: ' + err.message });
        }
        res.json({ success: true, message: 'All votes have been reset' });
      });
    });
  });
});

module.exports = router;
