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

export const load: PageServerLoad = async () => {
  return { content: getContent() };
};

export const actions: Actions = {
  contact: async ({ request, getClientAddress }) => {
    const data = await request.formData();
    const name = String(data.get('name') ?? '').trim();
    const dog = String(data.get('dog') ?? '').trim();
    const phone = String(data.get('phone') ?? '').trim();
    const message = String(data.get('message') ?? '').trim();

    if (!name || !phone || !message) {
      return fail(400, { error: 'Compila nome, telefono e messaggio.', name, dog, phone, message });
    }

    const entry = addSubmission({ name, dog, phone, message, ip: getClientAddress() });
    addNotification({
      type: 'submission',
      title: 'Nuova richiesta dal form',
      message: `${name}${dog ? ` (cane: ${dog})` : ''} ha inviato un messaggio.`,
      link: `/admin/submissions#${entry.id}`
    });
    return { success: true };
  }
};
