import { eq } from 'drizzle-orm';
import useDatabase from '~/composables/useDatabase';
import { characterTable } from '~/db/schema';
import { CharacterNotesValidation } from '#shared/character.util';

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

    const body = await readValidatedBody(e, CharacterNotesValidation.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({
        public_notes: body.data.public,
        private_notes: body.data.private,
    }).where(eq(characterTable.id, parseInt(id, 10))).run();

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