import { eq } from 'drizzle-orm';
import useDatabase from '~/composables/useDatabase';
import { characterTable } from '~/db/schema';
import { CharacterVariablesValidation } from '~/shared/character.util';
import type { CharacterVariables } from '~/types/character';

export default defineEventHandler(async (e) => {
    const id = getRouterParam(e, "id");
    if(!id)
    {
        setResponseStatus(e, 400);
        return;
    }

    const body = await readValidatedBody(e, CharacterVariablesValidation.safeParse);
    if(!body.success)
    {
        console.error(body.error);
        setResponseStatus(e, 400);
        throw body.error;
    }

    const db = useDatabase();
    const old = db.select({ id: characterTable.id, owner: characterTable.owner }).from(characterTable).where(eq(characterTable.id, parseInt(id, 10))).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.update(characterTable).set({
        variables: body.data
    }).where(eq(characterTable.id, parseInt(id, 10))).run();

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