import 'dotenv/config';
import { drizzle } from 'drizzle-orm/libsql';
import { sql, eq, and } from 'drizzle-orm';
import arrayShuffle from 'array-shuffle';
import {
  tasks_advanced,
  questions_advanced,
  categories_db,
} from '~~/db/schema';
import type { AdvancedQuestion } from '~~/shared/types';
import categories from '~~/categories';

export default defineEventHandler(async (event) => {
  const query = getQuery(event);
  const category = query.category;
  const lang = query.lang;

  if (
    typeof category !== 'string' ||
    !categories.includes(`${category.toUpperCase()}`)
  ) {
    throw createError({
      statusCode: 400,
      statusMessage: `category argument has to be equal to either: ${categories}`,
    });
  }

  if (
    typeof lang !== 'string' ||
    !['PL', 'EN', 'DE', 'UA'].includes(`${lang.toUpperCase()}`)
  ) {
    throw createError({
      statusCode: 400,
      statusMessage: `lang argument has to be equal to either: pl, en, de, ua`,
    });
  }

  async function getFromDb(
    points: number,
    limit: number,
    category: string,
    lang: string,
  ) {
    return await db
      .select({
        id: tasks_advanced.id,
        correct_answer: tasks_advanced.correct_answer,
        media_url: tasks_advanced.media_url,
        weight: tasks_advanced.weight,
        text: questions_advanced.text,
        answer_a: questions_advanced.answer_a,
        answer_b: questions_advanced.answer_b,
        answer_c: questions_advanced.answer_c,
      })
      .from(tasks_advanced)
      .leftJoin(
        questions_advanced,
        eq(questions_advanced.task_id, tasks_advanced.id),
      )
      .leftJoin(categories_db, eq(categories_db.task_id, tasks_advanced.id))
      .where(
        and(
          eq(categories_db.name, category.toUpperCase()),
          eq(questions_advanced.lang, lang.toUpperCase()),
          eq(tasks_advanced.weight, points),
        ),
      )
      .orderBy(sql`RANDOM()`)
      .limit(limit);
  }
  const db = drizzle(process.env.DATABASE_URL!);

  const randomizedQuestions: AdvancedQuestion[] = [];

  for (const [key, value] of Object.entries({ 1: 2, 2: 4, 3: 6 })) {
    randomizedQuestions.push(...(await getFromDb(+key, value, category, lang)));
  }
  return arrayShuffle(randomizedQuestions);
});
