import { db } from "@/db";
import { settings } from "@/db/schema";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";

export const SETTINGS_KEYS = {
  TARGET_HOURLY_RATE: "target_hourly_rate",
} as const;

export async function getSetting(key: string): Promise<string | null> {
  const rows = await db
    .select({ value: settings.value })
    .from(settings)
    .where(eq(settings.key, key))
    .limit(1);
  return rows[0]?.value ?? null;
}

// Pure upsert — NO revalidatePath. Safe to call during a server-component render
// (e.g. lazy-seeding a taxonomy pool). Use updateSetting when revalidation is
// desired (form submissions).
export async function writeSetting(key: string, value: string): Promise<void> {
  const existing = await getSetting(key);
  if (existing !== null) {
    await db
      .update(settings)
      .set({ value, updated_at: new Date() })
      .where(eq(settings.key, key));
  } else {
    await db.insert(settings).values({ key, value });
  }
}

export async function updateSetting(key: string, value: string): Promise<void> {
  await writeSetting(key, value);
  revalidatePath("/admin/impostazioni");
}

export async function getTargetHourlyRate(): Promise<number> {
  const value = await getSetting(SETTINGS_KEYS.TARGET_HOURLY_RATE);
  return value ? parseFloat(value) : 50;
}
