#!/usr/bin/env node

import dotenv from 'dotenv';
import { neon } from '@neondatabase/serverless';
import { generateUniqueSlug } from '../lib/slug-utils.js';

dotenv.config({ path: '.env.local' });

async function addSystemCollectionColumn() {
  const sql = neon(process.env.POSTGRES_URL);

  try {
    console.log('🔧 Adding is_system_collection column to collections table...');

    // Add the is_system_collection column
    await sql`
      ALTER TABLE collections 
      ADD COLUMN IF NOT EXISTS is_system_collection BOOLEAN DEFAULT false
    `;

    console.log('✅ Added is_system_collection column');

    // Get all existing users who don't have an "All My Cards" collection
    console.log('👥 Finding users without "All My Cards" collection...');
    
    const usersWithoutAllMyCards = await sql`
      SELECT u.id, u.email 
      FROM users u
      WHERE NOT EXISTS (
        SELECT 1 FROM collections c 
        WHERE c.user_id = u.id 
        AND c.name = 'All My Cards' 
        AND c.is_system_collection = true
      )
    `;

    console.log(`Found ${usersWithoutAllMyCards.length} users without "All My Cards" collection`);

    // Get existing slugs for uniqueness
    const existingSlugsData = await sql`SELECT slug FROM collections WHERE slug IS NOT NULL`;
    const existingSlugs = (existingSlugsData || []).map(row => row.slug);

    // Create "All My Cards" collection for each user
    for (const user of usersWithoutAllMyCards) {
      try {
        console.log(`Creating "All My Cards" for ${user.email}...`);
        
        // Generate unique slug
        const uniqueSlug = await generateUniqueSlug("All My Cards", existingSlugs);
        existingSlugs.push(uniqueSlug);

        // Create the collection
        const collectionResult = await sql`
          INSERT INTO collections (
            name, 
            description, 
            tcg, 
            is_public, 
            user_id, 
            slug, 
            is_system_collection,
            created_at, 
            updated_at
          )
          VALUES (
            'All My Cards',
            'Automatically contains all cards you mark as owned. This collection cannot be deleted or made public.',
            'All',
            false,
            ${user.id},
            ${uniqueSlug},
            true,
            CURRENT_TIMESTAMP,
            CURRENT_TIMESTAMP
          )
          RETURNING id
        `;

        const collection = collectionResult[0];

        // Create owner permission
        await sql`
          INSERT INTO collection_permissions (collection_id, user_id, role, status, created_at)
          VALUES (${collection.id}, ${user.id}, 'owner', 'active', CURRENT_TIMESTAMP)
        `;

        console.log(`  ✅ Created collection ID ${collection.id} with slug "${uniqueSlug}"`);

      } catch (error) {
        console.error(`  ❌ Failed to create collection for ${user.email}:`, error.message);
      }
    }

    console.log('\n🎉 Migration completed successfully!');
    console.log('\n📋 Summary:');
    console.log(`   • Added is_system_collection column to collections table`);
    console.log(`   • Created "All My Cards" collections for ${usersWithoutAllMyCards.length} existing users`);
    console.log(`   • New users will automatically get this collection on registration`);

  } catch (error) {
    console.error('❌ Migration failed:', error.message);
    console.error('Full error:', error);
    process.exit(1);
  }
}

if (import.meta.url === `file://${process.argv[1]}`) {
  addSystemCollectionColumn();
}

export { addSystemCollectionColumn };