// app/admin/actions.ts

'use server';

import { getConfig, updateConfig } from '../lib/config';
import { revalidatePath } from 'next/cache';

export async function saveConfigAction(prevState: { success?: boolean } | null | unknown, formData: FormData) {
    const config = await getConfig();

    let parsedClasses = [];
    try {
        const classesJSON = formData.get('classesJSON') as string;
        if (classesJSON) parsedClasses = JSON.parse(classesJSON);
    } catch (e) {
        console.error("Kunde inte parsa klasser", e);
    }

    const newConfig = {
        ...config,
        showBeachPromo: formData.get('showBeachPromo') === 'on',
        beachPage: {
            ...config.beachPage,
            matchStart: formData.get('matchStart') as string,
            festivalLink: formData.get('festivalLink') as string,
            closeReason: formData.get('closeReason') as string,
            otherInfo: formData.get('otherInfo') as string,
            prizesText: formData.get('prizesText') as string,
            rulesText: formData.get('rulesText') as string,
            classesIntroText: formData.get('classesIntroText') as string,
            classesOutroText: formData.get('classesOutroText') as string,
            isClosedOverride: formData.get('isClosedOverride') === 'on',
            classes: parsedClasses,
        }
    };

    await updateConfig(newConfig);
    revalidatePath('/');
    revalidatePath('/beach');

    return { success: true };
}