import { eq } from 'drizzle-orm';
import useDatabase from '~/composables/useDatabase';
import { characterAbilitiesTable, characterChoicesTable, 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 params = getRouterParam(e, "id");
    if(!params)
    {
        setResponseStatus(e, 400);
        return;
    }
    const id = parseInt(params, 10);

    const body = await readValidatedBody(e, CharacterValidation.safeParse);
    if(!body.success)
    {
        setResponseStatus(e, 400);
        return body.error.message;
    }

    const db = useDatabase();
    const old = db.select({ id: characterTable.id, owner: characterTable.owner }).from(characterTable).where(eq(characterTable.id, id)).get();
    
    if(!old)
    {
        setResponseStatus(e, 404);
        return;
    }

    const session = await getUserSession(e);
    if(!session.user || old.owner !== session.user.id || session.user.state !== 1)
    {
        setResponseStatus(e, 401);
        return;
    }
    
    db.transaction((tx) => {
        tx.update(characterTable).set({
            name: body.data.name,
            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,
        }).where(eq(characterTable.id, id)).run();

        tx.delete(characterLevelingTable).where(eq(characterLevelingTable.character, id)).run();
        tx.delete(characterTrainingTable).where(eq(characterTrainingTable.character, id)).run();
        tx.delete(characterAbilitiesTable).where(eq(characterAbilitiesTable.character, id)).run();
        tx.delete(characterChoicesTable).where(eq(characterChoicesTable.character, id)).run();

        const leveling = Object.entries(body.data.leveling).filter(e => e[1] !== undefined).map(e => ({ character: id, level: parseInt(e[0]), choice: e[1]! }));
        if(leveling.length > 0) tx.insert(characterLevelingTable).values(leveling).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]), 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], max: 0 }));
        if(abilities.length > 0) tx.insert(characterAbilitiesTable).values(abilities).run();
    });

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