import { drizzle } from "drizzle-orm/mysql2";
import { eq, and } from "drizzle-orm";
import * as schema from "./drizzle/schema.ts";

const { apprenants, inscriptions, sequences, attestations } = schema;

const db = drizzle(process.env.DATABASE_URL);

try {
  const results = await db
    .select({
      apprenant: {
        id: apprenants.id,
        nom: apprenants.nom,
        prenom: apprenants.prenom,
        email: apprenants.email,
      },
      inscription: {
        id: inscriptions.id,
        sequenceId: inscriptions.sequenceId,
      },
      sequence: {
        id: sequences.id,
        nom: sequences.nom,
      },
      attestation: {
        id: attestations.id,
        documentUrl: attestations.documentUrl,
        urlPdf: attestations.urlPdf,
        emailEnvoye: attestations.emailEnvoye,
        dateEnvoiEmail: attestations.dateEnvoiEmail,
      },
    })
    .from(inscriptions)
    .innerJoin(apprenants, eq(inscriptions.apprenantId, apprenants.id))
    .innerJoin(sequences, eq(inscriptions.sequenceId, sequences.id))
    .leftJoin(attestations, eq(attestations.inscriptionId, inscriptions.id))
    .where(
      and(
        eq(sequences.formationId, 1),
        eq(inscriptions.statut, "confirmee")
      )
    )
    .orderBy(apprenants.nom, apprenants.prenom);

  console.log("Success! Found", results.length, "results");
  console.log(JSON.stringify(results, null, 2));
} catch (error) {
  console.error("Error:", error.message);
  console.error("Full error:", error);
}

process.exit(0);
