const { Pool } = require('pg');
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, '../.env') });

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:`);
    colorsResult.rows.forEach(color => {
      console.log(`  - ${color.name} (${color.hex})`);
    });
    console.log('');
    
    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}`);
    
    // Show final state
    const finalCount = await pool.query(
      "SELECT COUNT(*) as count FROM filaments WHERE tip = 'PLA' AND finish = 'Basic' AND refill = '1'"
    );
    console.log(`- Total PLA Basic filaments with 1 refill: ${finalCount.rows[0].count}`);
    
    await pool.end();
    process.exit(0);
  } catch (error) {
    console.error('Error:', error);
    process.exit(1);
  }
}

addRefills();