import { error, redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import { getCalculatorBySlug, getCalculatorsByCategory, categories, getEffectiveCategory } from '$lib/data/calculators';
import { calculatorJsonLd, calculatorSeo, toJsonLd } from '$lib/seo';

export const load: PageServerLoad = ({ params, setHeaders }) => {
  const calc = getCalculatorBySlug(params.slug);

  if (!calc) {
    throw error(404, {
      message: `Calculator "${params.slug}" not found`
    });
  }

  const effectiveCategory = getEffectiveCategory(calc);
  const seo = calculatorSeo(calc);

  if (seo.canonicalSlug !== calc.slug) {
    throw redirect(301, `/${seo.canonicalSlug}`);
  }

  const related = getCalculatorsByCategory(effectiveCategory)
    .filter(c => c.slug !== calc.slug)
    .slice(0, 8);

  const categoryMeta = categories[effectiveCategory];
  if (seo.noindex) {
    setHeaders({
      'X-Robots-Tag': 'noindex, follow'
    });
  }

  return {
    calculator: calc,
    related,
    seo,
    jsonLd: toJsonLd(calculatorJsonLd(calc, seo.canonicalUrl)),
    category: effectiveCategory,
    categoryLabel: categoryMeta?.label ?? calc.category,
    categoryIcon: categoryMeta?.icon ?? '🔢'
  };
};
