import pkg from 'pg';

const { Pool } = pkg;

const pool = new Pool({
  connectionString: process.env.DATABASE_URL || 'postgresql://localhost:5432/tekdek_command_center'
});

async function seed() {
  const client = await pool.connect();
  
  try {
    console.log('🌱 Seeding sample data...');
    
    // Get user IDs
    const usersResult = await client.query('SELECT id FROM users ORDER BY id LIMIT 2');
    const parzivalId = usersResult.rows[0].id;
    const glytchtId = usersResult.rows[1].id;
    
    console.log(`   Users: ParzivalTD (${parzivalId}), Glytcht (${glytchtId})`);
    
    // Create sample projects
    const projectsData = [
      {
        name: 'Persona Portal v2.0',
        description: 'Redesign and relaunch the persona publishing platform',
        color_hex: '#3498db',
        icon_name: 'rocket'
      },
      {
        name: 'Command Center MVP',
        description: 'Build the core task management system',
        color_hex: '#e74c3c',
        icon_name: 'deploy'
      },
      {
        name: 'Documentation',
        description: 'Write and maintain all documentation',
        color_hex: '#2ecc71',
        icon_name: 'docs'
      }
    ];
    
    const projectIds = [];
    for (const proj of projectsData) {
      const result = await client.query(
        `INSERT INTO projects (name, description, color_hex, icon_name, owner_id, created_at, updated_at)
         VALUES ($1, $2, $3, $4, $5, NOW(), NOW())
         RETURNING id`,
        [proj.name, proj.description, proj.color_hex, proj.icon_name, parzivalId]
      );
      projectIds.push(result.rows[0].id);
      console.log(`   ✓ Project: ${proj.name} (ID: ${result.rows[0].id})`);
    }
    
    // Create sample tasks for first project
    const tasksData = [
      { title: 'Design new UI components', status: 'in_progress', assignee: parzivalId },
      { title: 'Implement API endpoints', status: 'backlog', assignee: glytchtId },
      { title: 'Write tests', status: 'backlog', assignee: parzivalId },
      { title: 'Update documentation', status: 'blocked', assignee: glytchtId },
      { title: 'Deploy to staging', status: 'done', assignee: parzivalId }
    ];
    
    console.log(`\n   📝 Creating tasks for project ${projectIds[0]}...`);
    for (let i = 0; i < tasksData.length; i++) {
      const task = tasksData[i];
      const result = await client.query(
        `INSERT INTO tasks (
          project_id, title, status, position, assignee_id, created_by, created_at, updated_at
        ) VALUES ($1, $2, $3, $4, $5, $6, NOW(), NOW())
        RETURNING id`,
        [projectIds[0], task.title, task.status, i, task.assignee, parzivalId]
      );
      console.log(`      ✓ ${task.title} (Status: ${task.status})`);
    }
    
    console.log('\n✅ Seed completed successfully!');
    
  } catch (error) {
    console.error('❌ Error seeding database:', error.message);
    process.exit(1);
  } finally {
    client.release();
    await pool.end();
  }
}

seed();
