import { eq } from "drizzle-orm";
import { siteConfig } from "@/config/site";
import { db } from "@/db";
import { siteContactSettings } from "@/db/schema";

const contactKeys = ["address", "phone"] as const;
type ContactKey = (typeof contactKeys)[number];

export type SiteContactSettings = { address: string; phone: string; phoneHref: string };

const defaults: Pick<SiteContactSettings, "address" | "phone"> = {
  address: siteConfig.address,
  phone: siteConfig.phone
};

function phoneHref(phone: string) {
  return `tel:${phone.replace(/[^\d+]/g, "")}`;
}

export async function getSiteContactSettings(): Promise<SiteContactSettings> {
  if (!db) return { ...defaults, phoneHref: siteConfig.phoneHref };
  const rows = await db.select().from(siteContactSettings);
  const values = Object.fromEntries(rows.map((row) => [row.key, row.value])) as Partial<Record<ContactKey, string>>;
  const phone = values.phone || defaults.phone;
  return { address: values.address || defaults.address, phone, phoneHref: phoneHref(phone) };
}

export async function saveSiteContactSettings(values: Pick<SiteContactSettings, "address" | "phone">) {
  if (!db) throw new Error("Database is not configured");
  for (const key of contactKeys) {
    await db.insert(siteContactSettings).values({ key, value: values[key], updatedAt: new Date() }).onConflictDoUpdate({
      target: siteContactSettings.key,
      set: { value: values[key], updatedAt: new Date() }
    });
  }
}
