import { eq } from "drizzle-orm";
import { getDb } from "../config/database.js";
import {
  questions,
  type Question,
  type NewQuestion,
} from "./questions.schema.js";

export class QuestionsRepository {
  async findById(id: string): Promise<Question | undefined> {
    const [result] = await getDb()
      .select()
      .from(questions)
      .where(eq(questions.id, id))
      .limit(1);
    return result;
  }

  async findByKnowledgePointId(knowledgePointId: string): Promise<Question[]> {
    return getDb()
      .select()
      .from(questions)
      .where(eq(questions.knowledgePointId, knowledgePointId));
  }

  async find(query?: {
    knowledgePointId?: string;
    type?: string;
    difficulty?: number;
    status?: string;
    page?: number;
    pageSize?: number;
  }): Promise<Question[]> {
    const db = getDb();
    let q = db.select().from(questions).$dynamic();
    if (query?.knowledgePointId) {
      q = q.where(eq(questions.knowledgePointId, query.knowledgePointId));
    }
    if (query?.type) {
      q = q.where(eq(questions.type, query.type));
    }
    if (query?.difficulty !== undefined) {
      q = q.where(eq(questions.difficulty, query.difficulty));
    }
    if (query?.status) {
      q = q.where(eq(questions.status, query.status));
    }
    const pageSize = query?.pageSize ?? 20;
    const page = query?.page ?? 1;
    return q.limit(pageSize).offset((page - 1) * pageSize);
  }

  async create(data: NewQuestion): Promise<void> {
    await getDb().insert(questions).values(data);
  }

  async update(id: string, data: Partial<NewQuestion>): Promise<void> {
    await getDb().update(questions).set(data).where(eq(questions.id, id));
  }

  async delete(id: string): Promise<void> {
    await getDb().delete(questions).where(eq(questions.id, id));
  }
}

export const questionsRepository = new QuestionsRepository();
