import { FreshContext } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts";
import { students } from "$root/databases/schema.ts";
import { and, eq } from "npm:drizzle-orm@0.45.2";
import {
  getPartialsConfig,
  makePartials,
} from "$root/defaults/makePartials.tsx";
import { State } from "$root/defaults/interfaces.ts";
import NotesView from "../(_islands)/NotesView.tsx";

async function Notes(
  _request: Request,
  context: FreshContext<State>,
) {
  const session =
    (context.state as unknown as { session: { sn: string; givenName: string } })
      .session;
  const { sn, givenName } = session;

  let numEtud: number | null = null;
  try {
    const student = await db
      .select()
      .from(students)
      .where(and(eq(students.nom, sn), eq(students.prenom, givenName)))
      .then((rows) => rows[0] ?? null);
    numEtud = student?.numEtud ?? null;
  } catch {
    // DB lookup failed — island will show fallback message
  }

  return <NotesView numEtud={numEtud} prenom={session.givenName} />;
}

export const config = getPartialsConfig();
export default makePartials(Notes);
