import {
  DEFAULT_PUBLIC_SITE_COPY,
  type PublicSiteCopy,
  type SiteHoursRow,
  SITE_CONTENT_ID,
} from "./site-content-defaults";
import { prisma } from "./prisma";

export type { PublicSiteCopy, SiteHoursRow } from "./site-content-defaults";
export { DEFAULT_PUBLIC_SITE_COPY, SITE_CONTENT_ID } from "./site-content-defaults";

function isHoursRow(x: unknown): x is SiteHoursRow {
  if (x === null || typeof x !== "object") return false;
  const o = x as Record<string, unknown>;
  return typeof o.days === "string" && typeof o.hours === "string";
}

function parseHoursJson(raw: unknown): SiteHoursRow[] {
  if (!Array.isArray(raw)) return [];
  return raw.filter(isHoursRow);
}

/** Textes publics (accueil, menu, galerie, horaires). */
export async function getPublicSiteContent(): Promise<PublicSiteCopy> {
  const row = await prisma.siteContent.findUnique({
    where: { id: SITE_CONTENT_ID },
  });
  if (!row) {
    return {
      ...DEFAULT_PUBLIC_SITE_COPY,
      hours: [...DEFAULT_PUBLIC_SITE_COPY.hours],
    };
  }
  const hours = parseHoursJson(row.hours);
  return {
    logoUrl: row.logoUrl?.trim() || DEFAULT_PUBLIC_SITE_COPY.logoUrl,
    heroEyebrow: row.heroEyebrow.trim() || DEFAULT_PUBLIC_SITE_COPY.heroEyebrow,
    heroTitle: row.heroTitle.trim() || DEFAULT_PUBLIC_SITE_COPY.heroTitle,
    heroSubtitle:
      row.heroSubtitle.trim() || DEFAULT_PUBLIC_SITE_COPY.heroSubtitle,
    heroBackgroundImageUrl:
      row.heroBackgroundImageUrl?.trim() ||
      DEFAULT_PUBLIC_SITE_COPY.heroBackgroundImageUrl,
    heroTextOverImage: row.heroTextOverImage ?? true,
    menuIntro: row.menuIntro.trim(),
    galleryIntro: row.galleryIntro.trim(),
    scheduleIntro:
      row.scheduleIntro.trim() || DEFAULT_PUBLIC_SITE_COPY.scheduleIntro,
    hours,
  };
}

export function parseHoursPayload(raw: unknown): SiteHoursRow[] | null {
  if (!Array.isArray(raw)) return null;
  const out: SiteHoursRow[] = [];
  for (const x of raw) {
    if (!isHoursRow(x)) return null;
    const days = x.days.trim();
    const hours = x.hours.trim();
    if (!days && !hours) continue;
    if (!days || !hours) return null;
    out.push({ days, hours });
  }
  return out;
}
