import mongoose from 'mongoose';

// Fixed ID shared with the Keycloak test users' householdIds attribute.
// Both must be kept in sync with docker/keycloak/realm-export.json.
const TEST_HOUSEHOLD_ID = new mongoose.Types.ObjectId('000000000000000000000001');

// SEED_MONGODB_URI is preferred so host-machine seeding always uses localhost,
// even when MONGODB_URI is set to the Docker-internal hostname in the environment.
const MONGODB_URI =
  process.env.SEED_MONGODB_URI ||
  process.env.MONGODB_URI ||
  'mongodb://meshitrack:devpassword@localhost:27017/meshitrack?authSource=admin&replicaSet=rs0';

async function seed() {
  console.log('Starting seed...');
  console.log(`Connecting to: ${MONGODB_URI.replace(/:[^:@]+@/, ':****@')}`);

  const conn = await mongoose.connect(MONGODB_URI);
  const db = conn.connection.db;

  if (!db) {
    throw new Error('Failed to get database reference');
  }

  // Clean existing dev data
  const collections = await db.listCollections().toArray();
  for (const col of collections) {
    await db.dropCollection(col.name);
  }
  console.log('Cleared existing collections');

  // Create household with the fixed ID that matches Keycloak user attributes.
  // User documents are not seeded here — they are created automatically via
  // upsertFromToken when each test user logs in for the first time.
  const householdsCollection = db.collection('households');
  await householdsCollection.insertOne({
    _id: TEST_HOUSEHOLD_ID,
    name: 'Test Household',
    ownerUserId: 'testuser1-keycloak-id',
    inviteCode: 'TESTCODE',
    members: [
      {
        userId: 'testuser1-keycloak-id',
        role: 'owner',
        joinedAt: new Date(),
      },
      {
        userId: 'testuser2-keycloak-id',
        role: 'member',
        joinedAt: new Date(),
      },
    ],
    settings: {
      timezone: 'UTC',
      currency: 'USD',
      language: 'en',
    },
    createdAt: new Date(),
    updatedAt: new Date(),
  });

  const householdId = TEST_HOUSEHOLD_ID.toString();

  console.log('Created test household');
  console.log('');
  console.log('=== Seed Complete ===');
  console.log('');
  console.log('Test Users (log in via Keycloak to create user documents):');
  console.log('  testuser1 / test1234  (owner, admin)');
  console.log('  testuser2 / test1234  (member)');
  console.log(`  Household ID: ${householdId}`);
  console.log(`  Invite Code:  TESTCODE`);
  console.log('');

  await conn.disconnect();
}

seed().catch((err) => {
  console.error('Seed failed:', err);
  process.exit(1);
});
