import { error, redirect } from '@sveltejs/kit';
import type { PageServerLoad, Actions } from './$types';
import { userForm,  SimulationCommunaute, Faisan } from '../../../helpers'
import { base } from '$app/paths'
import { base64encode } from '../../../base64';

export const load: PageServerLoad = async ({ params, platform }) => {
    console.log("load", params['id'])

    if (params['id'] == "nouveau") {
        let sim = Faisan.newSimulationCommunaute()
        console.log(JSON.stringify(sim))
        return <Faisan.GetProjetResp & { guest?: boolean }> {
            name: "",
            id: "",
            porteur: "",
            tel: "",
            adresse: "",
            simulation: { ... sim },
            guest: false
        }
    }

    let id_ = platform!.env.USER.jurisdiction('eu').idFromName("faisan")

    let [projet, img] = await Promise.all([
        userForm(platform!.env, id_, {
            GetProjet: params['id']
        }),
        platform!.env.projets.getWithMetadata(`photo.${params['id']}`, { type: 'arrayBuffer' })
    ])
    console.log("projet", JSON.stringify(projet))
    if(projet) {
        if(img?.value) {
            projet.img = base64encode(new Uint8Array(img.value))
        }
        return <Faisan.GetProjetResp> projet
    }

    throw error(404, 'Not found');
};

export const actions = {
    save: async ({ params, request, platform }) => {
        let id_ = platform!.env.USER.jurisdiction('eu').idFromName("faisan")
        let f = await request.formData()
        let data_ = f.get('data')
        let data
        if(data_) {
            console.log("data", data_)
            data = JSON.parse(data_ as string)
            if (!SimulationCommunaute(data)) {
                throw error(400, "Bad request")
            }
        } else {
            throw error(400, "Bad request")
        }
        let name = <string> f.get('name') || ''
        let porteur = <string> f.get('porteur') || ''
        let adresse = <string> f.get('adresse') || ''
        let tel = <string> f.get('tel') || ''
        let photo = <string | null> f.get('photo')

        console.log("params!", params)
        let pid
        if (params['id'] == "nouveau") {
            pid = await userForm(platform!.env, id_, {
                CreateProjet: {
                    name,
                    porteur,
                    tel,
                    adresse,
                    simulation: data
                }
            })
        } else {
            pid = params['id']
            await userForm(platform!.env, id_, {
                SaveProjet: {
                    id: params['id'],
                    name,
                    porteur,
                    tel,
                    adresse,
                    simulation: data
                }
            })
        }

        console.log(pid, !!photo)

        if(photo) {
            console.log("photo")
            try {
                console.log("f")
                console.log(photo)
                await platform!.env.projets.put(`photo.${id_.toString()}.${pid}`, photo)
                console.log("put")
            } catch(e) {
                console.log("Error", JSON.stringify(e))
            }
        }
        console.log("redirect", `${base}/projet/${pid}`)
        throw redirect(302, `${base}/projet/${pid}`)
    },
    del: async ({ cookies, params, platform }) => {

        let token = cookies.get('token')
        if (!token) {
            throw error(403, 'Forbidden');
        }
        let id_ = platform!.env.USER.jurisdiction('eu').idFromName("faisan")
        await userForm(platform!.env, id_, {
            DelProjet: {
                id: params['id'],
            }
        })

        throw redirect(302, `${base}`)
    },
} satisfies Actions