import { eq } from 'drizzle-orm';
import useDatabase from '~/composables/useDatabase';
import { characterTable } from '~/db/schema';

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

    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)
    {
        setResponseStatus(e, 401);
        return;
    }

    db.delete(characterTable).where(eq(characterTable.id, id)).run();

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