import { loadEnv } from '../src/config/env.js';
import { createDatabase } from '../src/db/database.js';
import { migrate } from '../src/db/migrations.js';
import { seedDatabase } from '../src/services/seed-data.js';

export async function createTestContext() {
  const env = loadEnv({
    NODE_ENV: 'test',
    DATABASE_DRIVER: 'pglite',
    PGLITE_DATA_DIR: ':memory:',
    APP_KEY: 'test-app-key-with-more-than-32-characters',
    SESSION_SECRET: 'test-session-secret-more-than-32-characters',
    SEED_DEMO_USERS: 'true'
  });
  const db = await createDatabase(env);
  await migrate(db);
  const credentials = await seedDatabase(db, true);
  const users = await db.query<{ id: string; username: string; warehouse_id: string | null }>('SELECT id, username, warehouse_id FROM users');
  const byUsername = Object.fromEntries(users.rows.map((user) => [user.username, user]));
  const requester = await db.query<{ id: string }>('SELECT id FROM requesters WHERE active = true LIMIT 1');
  const warehouse = await db.query<{ id: string }>('SELECT id FROM warehouses WHERE active = true LIMIT 1');
  return { env, db, credentials, users: byUsername, requesterId: requester.rows[0]!.id, warehouseId: warehouse.rows[0]!.id };
}

