require('dotenv').config({ path: '.env' });
const { drizzle } = require('drizzle-orm/mysql2');
const mysql = require('mysql2/promise');
const schema = require('./src/shared/db/schema');
const relations = require('./src/shared/db/relations');

(async () => {
  console.log('DATABASE_URL:', process.env.DATABASE_URL ? 'set' : 'not set');
  const pool = mysql.createPool({
    uri: process.env.DATABASE_URL,
    waitForConnections: true,
    connectionLimit: 5,
    queueLimit: 0,
  });
  const db = drizzle(pool, { schema: { ...schema, ...relations }, mode: 'default' });

  try {
    console.log('Trying homeworkAssignments.findMany with sourceExam relation...');
    const data = await db.query.homeworkAssignments.findMany({
      where: require('drizzle-orm').eq(schema.homeworkAssignments.creatorId, 'user_T_C1'),
      with: { sourceExam: true },
    });
    console.log('OK rows:', data.length);
    console.log('First row:', JSON.stringify(data[0], null, 2).substring(0, 500));
  } catch (e) {
    console.log('ERR:', e.message);
    console.log('Stack:', e.stack?.substring(0, 500));
  }
  await pool.end();
})();
