import { readJson, writeJson } from './storage';
import { randomUUID } from 'node:crypto';
import {
  buildDefaultContent,
  DEFAULT_IMAGES,
  DEFAULT_SLOTS,
  type SiteContent,
  type ImageSlot,
  type Testimonial
} from '$lib/content/defaults';

const FILE = 'content.json';

export function getContent(): SiteContent {
  const seed = buildDefaultContent();
  const stored = readJson<Partial<SiteContent>>(FILE, seed);
  return {
    copy: { ...seed.copy, ...(stored.copy ?? {}) },
    images: { ...seed.images, ...(stored.images ?? {}) },
    testimonials: stored.testimonials ?? seed.testimonials,
    seo: { ...seed.seo, ...(stored.seo ?? {}) }
  };
}

export function setCopy(id: string, value: string): void {
  const c = getContent();
  c.copy[id] = value;
  writeJson(FILE, c);
}

export function setCopyBulk(updates: Record<string, string>): void {
  const c = getContent();
  for (const [k, v] of Object.entries(updates)) c.copy[k] = v;
  writeJson(FILE, c);
}

export function setImage(id: string, patch: Partial<ImageSlot>): ImageSlot {
  const c = getContent();
  const current = c.images[id] ?? DEFAULT_IMAGES[id];
  if (!current) throw new Error(`Unknown image slot: ${id}`);
  const next: ImageSlot = {
    id,
    label: current.label,
    src: patch.src ?? current.src,
    alt: patch.alt ?? current.alt
  };
  c.images[id] = next;
  writeJson(FILE, c);
  return next;
}

export function resetImage(id: string): ImageSlot {
  const c = getContent();
  const fallback = DEFAULT_IMAGES[id];
  if (!fallback) throw new Error(`Unknown image slot: ${id}`);
  c.images[id] = { ...fallback };
  writeJson(FILE, c);
  return c.images[id];
}

export function setSeo(patch: Partial<SiteContent['seo']>): void {
  const c = getContent();
  c.seo = { ...c.seo, ...patch };
  writeJson(FILE, c);
}

export function listSlots() {
  return DEFAULT_SLOTS;
}

export function addTestimonial(input: Omit<Testimonial, 'id'>): Testimonial {
  const c = getContent();
  const entry: Testimonial = { id: `t_${randomUUID().slice(0, 8)}`, ...input };
  c.testimonials = [...c.testimonials, entry];
  writeJson(FILE, c);
  return entry;
}

export function updateTestimonial(id: string, patch: Partial<Omit<Testimonial, 'id'>>): Testimonial | null {
  const c = getContent();
  let updated: Testimonial | null = null;
  c.testimonials = c.testimonials.map((t) => {
    if (t.id !== id) return t;
    updated = { ...t, ...patch };
    return updated;
  });
  if (updated) writeJson(FILE, c);
  return updated;
}

export function deleteTestimonial(id: string): void {
  const c = getContent();
  c.testimonials = c.testimonials.filter((t) => t.id !== id);
  writeJson(FILE, c);
}
