#!/bin/bash
# Script to add 1 refill for each color in the database
# Run this on the API server or container with database access

# Create temporary Node.js script
cat > /tmp/add-refills.js << 'EOF'
const { Pool } = require('pg');

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  ssl: process.env.DATABASE_URL?.includes('amazonaws.com') ? { rejectUnauthorized: false } : false
});

async function addRefills() {
  try {
    console.log('Adding 1 refill for each color as PLA Basic filaments...\n');
    
    // First, get all colors
    const colorsResult = await pool.query('SELECT name, hex FROM colors ORDER BY name');
    console.log(`Found ${colorsResult.rows.length} colors in database\n`);
    
    let inserted = 0;
    let updated = 0;
    
    for (const color of colorsResult.rows) {
      // Check if PLA Basic already exists for this color
      const existing = await pool.query(
        'SELECT id, refill FROM filaments WHERE tip = $1 AND finish = $2 AND boja = $3',
        ['PLA', 'Basic', color.name]
      );
      
      if (existing.rows.length === 0) {
        // Insert new filament
        await pool.query(
          `INSERT INTO filaments (tip, finish, boja, boja_hex, refill, vakum, otvoreno, kolicina, cena) 
           VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
          ['PLA', 'Basic', color.name, color.hex, '1', '0 vakuum', '0 otvorena', 1, '3999']
        );
        console.log(`✓ Added PLA Basic ${color.name}`);
        inserted++;
      } else if (!existing.rows[0].refill || existing.rows[0].refill === '0') {
        // Update existing to have 1 refill
        await pool.query(
          'UPDATE filaments SET refill = $1 WHERE id = $2',
          ['1', existing.rows[0].id]
        );
        console.log(`✓ Updated PLA Basic ${color.name} to have 1 refill`);
        updated++;
      } else {
        console.log(`- PLA Basic ${color.name} already has ${existing.rows[0].refill} refill(s)`);
      }
    }
    
    console.log(`\nSummary:`);
    console.log(`- Inserted ${inserted} new PLA Basic filaments`);
    console.log(`- Updated ${updated} existing filaments to have 1 refill`);
    console.log(`- Total colors processed: ${colorsResult.rows.length}`);
    
    await pool.end();
    process.exit(0);
  } catch (error) {
    console.error('Error:', error);
    process.exit(1);
  }
}

addRefills();
EOF

# Run the script
cd /app && node /tmp/add-refills.js

# Clean up
rm /tmp/add-refills.js