import { db } from '../src/database/connection';
import { users, categories, pantryItems, orders } from '../src/database/schema';
import { supabaseAdmin } from '../src/config/supabase';

async function seedData() {
  try {
    console.log('🌱 Seeding database...\n');

    // Create admin user in Supabase Auth
    console.log('Creating admin user...');
    const { data: adminAuth, error: adminAuthError } = await supabaseAdmin.auth.admin.createUser({
      email: 'admin@pantry.com',
      password: 'admin123',
      user_metadata: {
        full_name: 'Admin User',
        role: 'admin'
      },
      email_confirm: true
    });

    if (adminAuthError && !adminAuthError.message.includes('already exists')) {
      console.error('Admin auth error:', adminAuthError);
    }

    if (adminAuth?.user) {
      await db.insert(users).values({
        id: adminAuth.user.id,
        email: 'admin@pantry.com',
        fullName: 'Admin User',
        role: 'admin'
      }).onConflictDoNothing();
      console.log('✓ Admin user created');
    }

    // Create regular users in Supabase Auth
    console.log('Creating regular users...');
    const regularUsers = [
      { email: 'john@example.com', fullName: 'John Doe' },
      { email: 'jane@example.com', fullName: 'Jane Smith' },
      { email: 'bob@example.com', fullName: 'Bob Johnson' }
    ];

    for (const userData of regularUsers) {
      const { data: userAuth } = await supabaseAdmin.auth.admin.createUser({
        email: userData.email,
        password: 'password123',
        user_metadata: {
          full_name: userData.fullName,
          role: 'user'
        },
        email_confirm: true
      });

      if (userAuth?.user) {
        await db.insert(users).values({
          id: userAuth.user.id,
          email: userData.email,
          fullName: userData.fullName,
          role: 'user'
        }).onConflictDoNothing();
        console.log(`✓ User created: ${userData.fullName}`);
      }
    }

    // Create categories
    console.log('\nCreating categories...');
    const [produceCategory] = await db.insert(categories).values({
      name: 'Produce',
      description: 'Fresh fruits and vegetables',
      color: '#4CAF50'
    }).returning().onConflictDoNothing();

    const [cannedCategory] = await db.insert(categories).values({
      name: 'Canned Goods',
      description: 'Canned and preserved foods',
      color: '#FF9800'
    }).returning().onConflictDoNothing();

    const [bakeryCategory] = await db.insert(categories).values({
      name: 'Bakery',
      description: 'Bread and baked goods',
      color: '#8D6E63'
    }).returning().onConflictDoNothing();

    const [grainsCategory] = await db.insert(categories).values({
      name: 'Grains',
      description: 'Rice, pasta, and grains',
      color: '#FDD835'
    }).returning().onConflictDoNothing();

    const [dairyCategory] = await db.insert(categories).values({
      name: 'Dairy',
      description: 'Milk, cheese, and dairy products',
      color: '#2196F3'
    }).returning().onConflictDoNothing();

    console.log('✓ Categories created');

    // Create pantry items
    console.log('\nCreating pantry items...');
    const now = new Date();
    const fiveDaysAgo = new Date(now.getTime() - 5 * 24 * 60 * 60 * 1000);
    const twoDaysAgo = new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000);
    const oneDayFromNow = new Date(now.getTime() + 1 * 24 * 60 * 60 * 1000);
    const threeDaysFromNow = new Date(now.getTime() + 3 * 24 * 60 * 60 * 1000);
    const fiveDaysFromNow = new Date(now.getTime() + 5 * 24 * 60 * 60 * 1000);
    const sevenDaysFromNow = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
    const fourteenDaysFromNow = new Date(now.getTime() + 14 * 24 * 60 * 60 * 1000);
    const thirtyDaysFromNow = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000);

    const items = [
      // Expired items (for testing alerts)
      { name: 'Expired Yogurt', categoryId: dairyCategory?.id, quantity: 12, unit: 'containers', expiryDate: fiveDaysAgo, isLowStock: false, lowStockThreshold: 5 },
      { name: 'Old Bread', categoryId: bakeryCategory?.id, quantity: 8, unit: 'loaves', expiryDate: twoDaysAgo, isLowStock: false, lowStockThreshold: 3 },
      // Expiring soon (critical - 1-2 days)
      { name: 'Milk', categoryId: dairyCategory?.id, quantity: 15, unit: 'gallons', expiryDate: oneDayFromNow, isLowStock: false, lowStockThreshold: 5 },
      // Expiring soon (high - 3-4 days)
      { name: 'Fresh Cheese', categoryId: dairyCategory?.id, quantity: 20, unit: 'blocks', expiryDate: threeDaysFromNow, isLowStock: false, lowStockThreshold: 10 },
      // Expiring soon (medium - 5-7 days)
      { name: 'Bananas', categoryId: produceCategory?.id, quantity: 3, unit: 'bunches', expiryDate: fiveDaysFromNow, isLowStock: true, lowStockThreshold: 5 },
      // Fresh items
      { name: 'Fresh Apples', categoryId: produceCategory?.id, quantity: 50, unit: 'lbs', expiryDate: fourteenDaysFromNow, isLowStock: false, lowStockThreshold: 10 },
      { name: 'Carrots', categoryId: produceCategory?.id, quantity: 25, unit: 'lbs', expiryDate: fourteenDaysFromNow, isLowStock: false, lowStockThreshold: 10 },
      { name: 'Canned Beans', categoryId: cannedCategory?.id, quantity: 100, unit: 'cans', expiryDate: thirtyDaysFromNow, isLowStock: false, lowStockThreshold: 20 },
      { name: 'Canned Tomatoes', categoryId: cannedCategory?.id, quantity: 75, unit: 'cans', expiryDate: thirtyDaysFromNow, isLowStock: false, lowStockThreshold: 20 },
      { name: 'Canned Soup', categoryId: cannedCategory?.id, quantity: 8, unit: 'cans', expiryDate: thirtyDaysFromNow, isLowStock: true, lowStockThreshold: 15 },
      { name: 'White Bread', categoryId: bakeryCategory?.id, quantity: 15, unit: 'loaves', expiryDate: sevenDaysFromNow, isLowStock: false, lowStockThreshold: 5 },
      { name: 'Whole Wheat Bread', categoryId: bakeryCategory?.id, quantity: 4, unit: 'loaves', expiryDate: sevenDaysFromNow, isLowStock: true, lowStockThreshold: 5 },
      { name: 'White Rice', categoryId: grainsCategory?.id, quantity: 40, unit: 'lbs', expiryDate: thirtyDaysFromNow, isLowStock: false, lowStockThreshold: 10 },
      { name: 'Pasta', categoryId: grainsCategory?.id, quantity: 30, unit: 'boxes', expiryDate: thirtyDaysFromNow, isLowStock: false, lowStockThreshold: 10 },
      { name: 'Milk', categoryId: dairyCategory?.id, quantity: 20, unit: 'gallons', expiryDate: sevenDaysFromNow, isLowStock: false, lowStockThreshold: 5 },
      { name: 'Cheese', categoryId: dairyCategory?.id, quantity: 12, unit: 'blocks', expiryDate: fourteenDaysFromNow, isLowStock: false, lowStockThreshold: 5 },
    ];

    for (const item of items) {
      await db.insert(pantryItems).values(item);
    }
    console.log(`✓ ${items.length} pantry items created`);

    // Create some sample orders
    console.log('\nCreating sample orders...');
    const allUsers = await db.select().from(users);
    const regularUsersList = allUsers.filter(u => u.role === 'user');

    if (regularUsersList.length > 0) {
      for (const user of regularUsersList) {
        await db.insert(orders).values({
          userId: user.id,
          name: 'Weekly Food Box',
          quantity: 5,
          unit: Math.random() > 0.5 ? 'ready' : 'pending',
          priority: 'Fri 10AM-2PM',
          notes: 'Includes fresh produce, canned goods, and bread',
          isPurchased: false
        });
      }
      console.log(`✓ ${regularUsersList.length} orders created`);
    }

    console.log('\n✅ Database seeded successfully!');
    console.log('\n📝 Test Credentials:');
    console.log('   Admin: admin@pantry.com / admin123');
    console.log('   User:  john@example.com / password123');
    process.exit(0);
  } catch (error) {
    console.error('❌ Error seeding database:', error);
    process.exit(1);
  }
}

seedData();

