import { error } from '@sveltejs/kit'
import type { PageServerLoad, Actions } from './$types'
import { userForm, Grain, save, del } from '../../../helpers'

export const load: PageServerLoad = async ({ params, platform }) => {
    console.log('load', params['id'])
    if (!platform) {
        return null
    }
    if (params['id'] == 'nouveau') {
        const sim = Grain.newSimulationCommunaute()
        console.log(JSON.stringify(sim))
        return <Grain.GetProjetResp & { guest?: boolean }>{
            nom: '',
            id: '',
            porteur: '',
            tel: '',
            adresse: '',
            simulation: { ...sim },
            guest: false,
            email: 'grain@coturnix.fr',
            prms: [],
            centrales: [],
        }
    }

    const id_ = platform.env.USER.idFromName('grain')

    const projet = await userForm(platform.env, id_, {
        GetProjet: params['id'],
    })
    console.log('projet', JSON.stringify(projet))
    if (projet) {
        return <Grain.GetProjetResp>projet
    }

    throw error(404, 'Not found')
}

export const actions = {
    save: async ({ params, request, platform }) => {
        if (!platform) {
            return null
        }
        const id_ = platform.env.USER.idFromName('grain')
        return await save(id_, params, request, platform)
    },
    del: async ({ params, platform }) => {
        if (!platform) {
            return null
        }
        const id_ = platform.env.USER.idFromName('grain')
        return await del(id_, params, platform)
    },
} satisfies Actions