import "server-only";

import { cache } from "react";
import type { z } from "zod";

import { cmsData, cmsPaths, withFallback } from "@/lib/cms/api";

import { settingSchemas, type SettingKey } from "./schemas";

/** Where each setting lives on the Laravel CMS. */
const settingPaths: Record<SettingKey, string> = {
  blogDefaults: cmsPaths.blogDefaults,
};

/**
 * A setting parsed through its schema. Missing or outdated values (or a CMS
 * that doesn't serve settings yet) fall back to the schema defaults.
 */
export const getSetting = cache(
  async <K extends SettingKey>(
    key: K,
  ): Promise<z.infer<(typeof settingSchemas)[K]>> => {
    const schema = settingSchemas[key];
    const value = await withFallback(cmsData<unknown>(settingPaths[key]), {});
    const parsed = schema.safeParse(value ?? {});
    return parsed.success ? parsed.data : schema.parse({});
  },
);

export const getBlogDefaults = () => getSetting("blogDefaults");
