import { hash } from "bun";
import { eq } from "drizzle-orm";
import useDatabase from "~/composables/useDatabase";
import { usersTable } from "~/db/schema";

export default defineEventHandler(async (e) => {
    const session = await getUserSession(e);

    if(!session || !session.user || !session.user.id)
    {
        return createError({
            statusCode: 401,
            message: 'Unauthorized',
        });
    }

    const id = getRouterParam(e, 'id');

    if(!id)
    {
        return createError({
            statusCode: 403,
            message: 'Forbidden',
        });
    }
    if(session.user.id.toString() !== id)
    {
        return createError({
            statusCode: 401,
            message: 'Unauthorized',
        });
    }

    const db = useDatabase();
    const data = db.select({ id: usersTable.id, email: usersTable.email, username: usersTable.username, hash: usersTable.hash, state: usersTable.state }).from(usersTable).where(eq(usersTable.id, session.user.id)).get();

    if(!data)
    {
        return createError({
            statusCode: 401,
            message: 'Unauthorized',
        });
    }
    if(data.state === 1)
    {
        setResponseStatus(e, 200);
        return;
    }

    const emailId = hash('register' + data.id + data.hash, Date.now());
    const timestamp = Date.now() + 1000 * 60 * 60;

    await runTask('validation', {
        payload: {
            type: 'validation',
            id: emailId, timestamp,
        }
    });
    await runTask('mail', {
        payload: {
            type: 'mail',
            to: [data.email],
            template: 'registration',
            data: {
                id: emailId, timestamp,
                userId: id,
                username: data.username,
            },
        }
    });

    setResponseStatus(e, 200);
    return;
})