import type { Actions, PageServerLoad } from './$types';
import { fail } from '@sveltejs/kit';
import { getContent, setCopyBulk, setSeo } from '$lib/server/content';
import { DEFAULT_SLOTS } from '$lib/content/defaults';
import { computeHealth } from '$lib/server/health';
import { addNotification } from '$lib/server/notifications';

const DROP_THRESHOLD = 8;

export const load: PageServerLoad = () => {
  const content = getContent();
  return {
    slots: DEFAULT_SLOTS,
    copy: content.copy,
    seo: content.seo
  };
};

export const actions: Actions = {
  saveCopy: async ({ request }) => {
    const form = await request.formData();
    const updates: Record<string, string> = {};
    const knownIds = new Set(DEFAULT_SLOTS.map((s) => s.id));
    for (const [key, val] of form.entries()) {
      if (!key.startsWith('slot:')) continue;
      const id = key.slice(5);
      if (!knownIds.has(id)) continue;
      updates[id] = String(val);
    }
    if (!Object.keys(updates).length) return fail(400, { error: 'Nessuna modifica da salvare.' });

    const before = computeHealth();
    setCopyBulk(updates);
    const after = computeHealth();

    if (before.seo - after.seo >= DROP_THRESHOLD) {
      addNotification({
        type: 'seo_drop',
        title: 'Punteggio SEO in calo',
        message: `SEO passato da ${before.seo}/100 a ${after.seo}/100 dopo l'ultima modifica.`,
        link: '/admin/copy'
      });
    }
    if (before.geo - after.geo >= DROP_THRESHOLD) {
      addNotification({
        type: 'geo_drop',
        title: 'Punteggio GEO in calo',
        message: `GEO passato da ${before.geo}/100 a ${after.geo}/100 dopo l'ultima modifica.`,
        link: '/admin/copy'
      });
    }
    return { success: true, count: Object.keys(updates).length };
  },
  saveSeo: async ({ request }) => {
    const form = await request.formData();
    const title = String(form.get('title') ?? '').trim();
    const description = String(form.get('description') ?? '').trim();
    const keywords = String(form.get('keywords') ?? '').trim();
    const ogImage = String(form.get('ogImage') ?? '').trim();
    const primary = String(form.get('primaryKeywords') ?? '')
      .split(',')
      .map((s) => s.trim())
      .filter(Boolean);
    const geoRegion = String(form.get('geoRegion') ?? '').trim();
    const geoPlacename = String(form.get('geoPlacename') ?? '').trim();

    const before = computeHealth();
    setSeo({
      title,
      description,
      keywords,
      ogImage,
      primaryKeywords: primary,
      geoRegion,
      geoPlacename
    });
    const after = computeHealth();

    if (before.seo - after.seo >= DROP_THRESHOLD) {
      addNotification({
        type: 'seo_drop',
        title: 'Punteggio SEO in calo',
        message: `Cambiate le keyword primarie: SEO ${before.seo} → ${after.seo}.`,
        link: '/admin/copy'
      });
    }
    return { seoSaved: true };
  }
};
