import 'dotenv/config';
import { drizzle } from 'drizzle-orm/libsql';
import { sql, eq, and } from 'drizzle-orm';
import arrayShuffle from 'array-shuffle';
import { tasks, questions, categories_db } from '~~/db/schema';
import type { BasicQuestion } 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.id,
        correct_answer: tasks.correct_answer,
        media_url: tasks.media_url,
        weight: tasks.weight,
        text: questions.text,
      })
      .from(tasks)
      .leftJoin(questions, eq(questions.task_id, tasks.id))
      .leftJoin(categories_db, eq(categories_db.task_id, tasks.id))
      .where(
        and(
          eq(categories_db.name, category.toUpperCase()),
          eq(questions.lang, lang.toUpperCase()),
          eq(tasks.weight, points),
        ),
      )
      .orderBy(sql`RANDOM()`)
      .limit(limit);
  }
  const db = drizzle(process.env.DATABASE_URL!);

  const randomizedQuestions: BasicQuestion[] = [];

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