import { desc, eq } from "drizzle-orm";
import { db } from "./index";
import { presse } from "./schema";
import type { PresseItem } from "@/lib/presse-types";
import { formatDatePresse } from "@/lib/formatDatePresse";

export type { PresseItem };
export { formatDatePresse };

/** Normalise externalUrl en string ou null (évite crash si le driver renvoie autre chose). */
function toExternalUrl(value: unknown): string | null {
  if (value == null) return null;
  const s = typeof value === "string" ? value : String(value).trim();
  const trimmed = s.trim();
  if (trimmed === "" || trimmed.toLowerCase() === "null") return null;
  return trimmed;
}

/** Normalise la date (chaîne YYYY-MM-DD ou objet Date) en YYYY-MM-DD. */
function toIsoDate(value: string | Date | null | undefined): string {
  if (value == null) return "";
  if (typeof value === "object" && "toISOString" in value) {
    return (value as Date).toISOString().slice(0, 10);
  }
  const s = String(value).trim();
  if (!s || s === "null" || s === "undefined") return "";
  const match = s.match(/^(\d{4})-(\d{2})-(\d{2})/);
  return match ? `${match[1]}-${match[2]}-${match[3]}` : s;
}

export async function getAllPresse(): Promise<PresseItem[]> {
  if (!db) return [];
  try {
    const rows = await db
      .select()
      .from(presse)
      .orderBy(desc(presse.date));
    return (rows as Record<string, unknown>[]).map((row) =>
      rowToPresseItem(row)
    );
  } catch {
    return [];
  }
}

/** Construit un PresseItem sérialisable (pas de Date/Buffer) pour le client. */
function rowToPresseItem(r: Record<string, unknown>): PresseItem {
  return {
    id: Number(r.id),
    type: String(r.type ?? ""),
    title: String(r.title ?? ""),
    excerpt: String(r.excerpt ?? ""),
    content: String(r.content ?? ""),
    image: String(r.image ?? ""),
    date: toIsoDate(r.date as string | Date | null | undefined) || "1970-01-01",
    source: String(r.source ?? ""),
    duration:
      r.duration != null && r.duration !== "" && String(r.duration).toLowerCase() !== "null"
        ? String(r.duration)
        : null,
    externalUrl: toExternalUrl(r.externalUrl ?? r.external_url),
  };
}

export async function getPresseById(id: number): Promise<PresseItem | null> {
  if (!db) return null;
  try {
    const rows = await db.select().from(presse).where(eq(presse.id, id)).limit(1);
    const row = rows[0] ?? null;
    if (!row) return null;
    return rowToPresseItem(row as Record<string, unknown>);
  } catch {
    return null;
  }
}
