import {
  DEFAULT_CUSTOM_WAFFLE,
  type CustomWaffleConfig,
} from "./custom-waffle";
import { normalizeImageUrl } from "./image-url";
import { prisma } from "./prisma";
import { SITE_CONTENT_ID } from "./site-content-defaults";

export async function getCustomWaffleConfig(): Promise<CustomWaffleConfig> {
  const row = await prisma.siteContent.findUnique({
    where: { id: SITE_CONTENT_ID },
    select: {
      customWaffleTitle: true,
      customWaffleDescription: true,
      customWaffleBasePrice: true,
      customWaffleImageUrl: true,
      customWaffleVisible: true,
    },
  });

  if (!row) {
    return { ...DEFAULT_CUSTOM_WAFFLE };
  }

  const basePrice =
    Number.isFinite(row.customWaffleBasePrice) && row.customWaffleBasePrice >= 0
      ? row.customWaffleBasePrice
      : DEFAULT_CUSTOM_WAFFLE.basePrice;

  return {
    title: row.customWaffleTitle.trim() || DEFAULT_CUSTOM_WAFFLE.title,
    description:
      row.customWaffleDescription.trim() || DEFAULT_CUSTOM_WAFFLE.description,
    basePrice,
    imageUrl:
      row.customWaffleImageUrl?.trim() || DEFAULT_CUSTOM_WAFFLE.imageUrl,
    visible: row.customWaffleVisible,
  };
}

export function parseCustomWafflePayload(
  body: Record<string, unknown>
): { data: CustomWaffleConfig; error?: undefined } | { data?: undefined; error: string } {
  const title = String(body.title ?? "").trim();
  const description = String(body.description ?? "").trim();
  if (!title) return { error: "Le titre est requis" };
  if (!description) return { error: "La description est requise" };

  const rawPrice =
    typeof body.basePrice === "number"
      ? body.basePrice
      : parseFloat(String(body.basePrice ?? "").replace(",", "."));
  if (!Number.isFinite(rawPrice) || rawPrice < 0) {
    return { error: "Prix minimum invalide" };
  }

  const imageUrl =
    normalizeImageUrl(String(body.imageUrl ?? "")) ??
    DEFAULT_CUSTOM_WAFFLE.imageUrl;

  return {
    data: {
      title,
      description,
      basePrice: rawPrice,
      imageUrl,
      visible: body.visible !== false,
    },
  };
}
