import { eq } from 'drizzle-orm';
import useDatabase from '~/composables/useDatabase';
import { characterAbilitiesTable, characterLevelingTable, characterTable, characterTrainingTable } 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().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;
    }
    
    try
    {
        const _id = db.transaction((tx) => {
            const _id = tx.insert(characterTable).values({
                name: old.name,
                owner: session.user!.id,
                people: old.people!,
                level: old.level,
                aspect: old.aspect,
                notes: old.notes,
                variables: old.variables,
                visibility: old.visibility,
                thumbnail: old.thumbnail,
            }).returning({ id: characterTable.id }).get().id;
    
            const leveling = tx.select().from(characterLevelingTable).where(eq(characterLevelingTable.character, parseInt(id, 10))).all();
            if(leveling.length > 0) tx.insert(characterLevelingTable).values(leveling.map(e => ({ character: _id, level: e.level, choice: e.choice }))).run();

            const training = tx.select().from(characterTrainingTable).where(eq(characterTrainingTable.character, parseInt(id, 10))).all();
            if(training.length > 0) tx.insert(characterTrainingTable).values(training.map(e => ({ character: _id, stat: e.stat, level: e.level, choice: e.choice }))).run();

            const abilities = tx.select().from(characterAbilitiesTable).where(eq(characterAbilitiesTable.character, parseInt(id, 10))).all();
            if(abilities.length > 0) tx.insert(characterAbilitiesTable).values(abilities.map(e => ({ character: _id, ability: e.ability, value: e.value, max: e.max }))).run();
            
            return _id;
        });
    
        setResponseStatus(e, 201);
        return _id;
    }
    catch(_e)
    {
        setResponseStatus(e, 201);
        throw _e;
    }
});