import useDatabase from '~/composables/useDatabase';
import { characterTable } from '~/db/schema';
import { group } from '~/shared/general.util';
import type { Character, CharacterVariables, Level, MainStat, TrainingLevel } from '~/types/character';

export default defineEventHandler(async (e) => {
    const id = getRouterParam(e, "id");

    if(!id)
    {
        setResponseStatus(e, 400);
        return;
    }

    const session = await getUserSession(e);

    if(!session.user)
    {
        setResponseStatus(e, 401);
        return;
    }

    const db = useDatabase();
    const character = db.query.characterTable.findFirst({
        with: {
            abilities: true,
            levels: true,
            training: true,
            choices: true,
            user: {
                columns: { username: true }
            }
        },
        where: (character, { eq, and }) => and(eq(character.id, parseInt(id, 10)), eq(characterTable.owner, session.user!.id)),
    }).sync();

    if(character !== undefined)
    {
        return {
            id: character.id,

            name: character.name,
            people: character.people,
            level: character.level,
            aspect: character.aspect,
            notes: { public: character.public_notes, private: session.user?.id === character.owner ? character.private_notes : undefined },
            variables: character.variables,

            training: character.training.reduce((p, v) => { p[v.stat] ??= {}; p[v.stat][v.level as TrainingLevel] = v.choice; return p; }, {} as Record<MainStat, Partial<Record<TrainingLevel, number>>>),
            leveling: group(character.levels, "level", "choice"),
            abilities: group(character.abilities, "ability", "value"),
            choices: character.choices.reduce((p, v) => { p[v.id] ??= []; p[v.id]?.push(v.choice); return p; }, {} as Record<string, number[]>),

            owner: character.owner,
            username: character.user.username,
            visibility: character.visibility,
        } as Character;
    }
    
    setResponseStatus(e, 404);
    return;
});