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

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, path.join(__dirname, '../public/images'));
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname));
  }
});

const upload = multer({ storage: storage });

router.get('/', (req, res) => {
  const sql = `
    SELECT c.*, p.title as position_title 
    FROM candidates c 
    JOIN positions p ON c.position_id = p.id
  `;
  db.all(sql, [], (err, rows) => {
    if (err) return res.status(500).json({ error: err.message });
    res.json(rows);
  });
});

router.post('/', upload.single('image'), (req, res) => {
  const { name, position_id, bio } = req.body;
  const imageUrl = req.file ? `/public/images/${req.file.filename}` : null;

  db.run(
    'INSERT INTO candidates (name, position_id, image_url, bio) VALUES (?, ?, ?, ?)',
    [name, position_id, imageUrl, bio],
    function(err) {
      if (err) return res.status(500).json({ error: err.message });
      res.json({ id: this.lastID, name, position_id, imageUrl });
    }
  );
});

router.delete('/:id', (req, res) => {
  const { id } = req.params;
  
  db.run('DELETE FROM votes WHERE candidate_id = ?', [id], (err) => {
    if (err) {
      console.error('Error deleting votes:', err.message);
      return res.status(500).json({ error: 'Failed to delete candidate votes: ' + err.message });
    }

    db.run('DELETE FROM candidates WHERE id = ?', [id], function(err) {
      if (err) {
        console.error('Error deleting candidate:', err.message);
        return res.status(500).json({ error: 'Failed to delete candidate: ' + err.message });
      }
      res.json({ success: true, message: 'Candidate deleted successfully' });
    });
  });
});

module.exports = router;
