const express = require('express');
const router = express.Router();
const { authenticate } = require('../middleware/auth');

// Temporary migration endpoint - remove after use
router.post('/add-basic-refills', authenticate, async (req, res) => {
  const pool = req.app.locals.pool;
  
  try {
    // First, let's insert filaments for all existing colors
    const result = await pool.query(`
      INSERT INTO filaments (tip, finish, boja, boja_hex, refill, vakum, otvoreno, kolicina, cena)
      SELECT 
          'PLA' as tip,
          'Basic' as finish,
          c.name as boja,
          c.hex as boja_hex,
          '1' as refill,
          '0 vakuum' as vakum,
          '0 otvorena' as otvoreno,
          1 as kolicina,
          '3999' as cena
      FROM colors c
      WHERE NOT EXISTS (
          -- Only insert if this exact combination doesn't already exist
          SELECT 1 FROM filaments f 
          WHERE f.tip = 'PLA' 
          AND f.finish = 'Basic' 
          AND f.boja = c.name
      )
    `);
    
    // Update any existing PLA Basic filaments to have at least 1 refill
    const updateResult = await pool.query(`
      UPDATE filaments
      SET refill = '1'
      WHERE tip = 'PLA' 
      AND finish = 'Basic'
      AND (refill IS NULL OR refill = '0' OR refill = '')
    `);
    
    // Show summary
    const summary = await pool.query(`
      SELECT COUNT(*) as count 
      FROM filaments 
      WHERE tip = 'PLA' 
      AND finish = 'Basic' 
      AND refill = '1'
    `);
    
    res.json({
      success: true,
      inserted: result.rowCount,
      updated: updateResult.rowCount,
      total: summary.rows[0].count
    });
  } catch (error) {
    console.error('Migration error:', error);
    res.status(500).json({ error: 'Migration failed', details: error.message });
  }
});

module.exports = router;