import { asc } from "drizzle-orm";
import { db } from "./index";
import { agenda } from "./schema";

export type AgendaEvent = {
  id: number;
  type: string;
  title: string;
  date: string;
  time: string;
  location: string;
  description: string;
  important: boolean | null;
};

export async function getAllAgenda(): Promise<AgendaEvent[]> {
  if (!db) return [];
  try {
    const rows = await db
      .select()
      .from(agenda)
      .orderBy(asc(agenda.date), asc(agenda.time));
    return rows as AgendaEvent[];
  } catch {
    return [];
  }
}

function isPastEvent(dateStr: string): boolean {
  const today = new Date();
  const y = today.getFullYear();
  const m = String(today.getMonth() + 1).padStart(2, "0");
  const d = String(today.getDate()).padStart(2, "0");
  const todayStr = `${y}-${m}-${d}`;
  return dateStr < todayStr;
}

/** Retourne les prochains événements (date >= aujourd'hui), triés par date/heure, limités à `limit`. */
export async function getUpcomingAgenda(limit = 6): Promise<AgendaEvent[]> {
  const all = await getAllAgenda();
  return all.filter((e) => !isPastEvent(e.date)).slice(0, limit);
}
