import { z } from 'zod/v4';
import useDatabase from '~/composables/useDatabase';
import { characterAbilitiesTable, characterLevelingTable, characterTable, characterTrainingTable } from '~/db/schema';
import { CharacterValidation } from '#shared/character.util';
import { type Ability, type MainStat } from '~/types/character';


export default defineEventHandler(async (e) => {
    const body = await readValidatedBody(e, CharacterValidation.extend({ id: z.unknown(), }).safeParse);
    if(!body.success)
    {
        setResponseStatus(e, 400);
        return body.error.message;
    }

    const session = await getUserSession(e);
    if(!session.user || session.user.state !== 1)
    {
        setResponseStatus(e, 401);
        return;
    }

    const db = useDatabase();

    try
    {
        const id = db.transaction((tx) => {
            const id = tx.insert(characterTable).values({
                name: body.data.name,
                owner: session.user!.id,
                people: body.data.people!,
                level: body.data.level,
                aspect: body.data.aspect,
                public_notes: body.data.notes.public,
                private_notes: body.data.notes.private,
                variables: body.data.variables,
                visibility: body.data.visibility,
                thumbnail: body.data.thumbnail,
            }).returning({ id: characterTable.id }).get().id;
    
            if(Object.keys(body.data.leveling).length > 0) tx.insert(characterLevelingTable).values(Object.entries(body.data.leveling).filter(e => e[1] !== undefined).map(e => ({ character: id, level: parseInt(e[0], 10), choice: e[1]! }))).run();

            const training = Object.entries(body.data.training).flatMap(e => Object.entries(e[1]).filter(e => e[1] !== undefined).map(_e => ({ character: id, stat: e[0] as MainStat, level: parseInt(_e[0], 10), choice: _e[1]! })));
            if(training.length > 0) tx.insert(characterTrainingTable).values(training).run();

            const abilities = Object.entries(body.data.abilities).filter(e => e[1] !== undefined).map(e => ({ character: id, ability: e[0] as Ability, value: e[1] }));
            if(abilities.length > 0) tx.insert(characterAbilitiesTable).values(abilities).run();
    
            return id;
        });
    
        setResponseStatus(e, 201);
        return id;
    }
    catch(_e)
    {
        console.error(_e);

        setResponseStatus(e, 500);
        return;
    }
});