import type { Actions, PageServerLoad } from './$types';
import { fail } from '@sveltejs/kit';
import { getContent, setCopyBulk } from '$lib/server/content';

const CONTACT_FIELDS = [
  'contact.info_title',
  'contact.phone_label',
  'contact.phone_value',
  'contact.email_label',
  'contact.email_value',
  'contact.wa_label',
  'contact.wa_value'
] as const;

export const load: PageServerLoad = () => {
  const content = getContent();
  const values: Record<string, string> = {};
  for (const id of CONTACT_FIELDS) values[id] = content.copy[id] ?? '';
  return { values };
};

export const actions: Actions = {
  save: async ({ request }) => {
    const form = await request.formData();
    const updates: Record<string, string> = {};
    for (const id of CONTACT_FIELDS) {
      const v = form.get(id);
      if (v === null) continue;
      updates[id] = String(v).trim();
    }
    if (!Object.keys(updates).length) return fail(400, { error: 'Nessuna modifica da salvare.' });
    setCopyBulk(updates);
    return { success: true, count: Object.keys(updates).length };
  }
};
