import { createCoreAPIClient } from "@/lib/features/coreClient";
import type { CoreResponse } from "@/lib/features/types";

/**
 * Console-wide settings.
 *
 * Backs the promo appearance theme and the Viewpoint bookings table's column
 * choice. The theme used to live only in each
 * browser's localStorage, which made it a per-device preference — a super admin
 * picking an accent changed it on their own machine and nowhere else. These
 * endpoints move the value server-side so one super admin sets the look for
 * everybody.
 */

const coreClient = createCoreAPIClient();

const BASE = "/v1/admin-console/console-settings";

/** Keys the endpoint accepts; anything else returns 404 from core. */
export type ConsoleSettingKey =
  | "promo-appearance"
  | "viewpoint-booking-columns";

export interface ConsoleSetting<T> {
  key: string;
  /** Null when the setting has never been saved — the client uses its defaults. */
  value: T | null;
  updatedAt: string | null;
  updatedBy: string | null;
}

export async function getConsoleSetting<T>(
  key: ConsoleSettingKey,
  init?: RequestInit,
): Promise<CoreResponse<ConsoleSetting<T>>> {
  return await coreClient<ConsoleSetting<T>>(`${BASE}/${key}`, {
    method: "GET",
    ...init,
  });
}

/** Super-admin only; core returns 403 for anyone else. */
export async function putConsoleSetting<T>(
  key: ConsoleSettingKey,
  value: T,
): Promise<CoreResponse<ConsoleSetting<T>>> {
  return await coreClient<ConsoleSetting<T>>(`${BASE}/${key}`, {
    method: "PUT",
    body: JSON.stringify({ value }),
  });
}
