import { eq, getTableColumns, lte } from "drizzle-orm";
import { z } from "zod";
import useDatabase from "~/composables/useDatabase";
import { emailValidationTable, usersTable } from "~/db/schema";

const schema = z.object({
    h: z.coerce.string(),
    i: z.coerce.string(),
    u: z.coerce.number(),
    t: z.coerce.number(),
});

export default defineEventHandler(async (e) => {
    const query = await getValidatedQuery(e, schema.safeParse);

    if(!query.success)
        throw query.error;

    if(Bun.hash('1' + query.data.u.toString(), query.data.t).toString() !== query.data.h)
    {
        return createError({
            statusCode: 400,
            message: 'Lien incorrect',
        });
    }
    if(Date.now() > query.data.t + (60 * 60 * 1000))
    {
        return createError({
            statusCode: 400,
            message: 'Le lien a expiré',
        });
    }

    const db = useDatabase();
    const validate = db.select(getTableColumns(emailValidationTable)).from(emailValidationTable).where(eq(emailValidationTable.id, query.data.i)).get();

    if(!validate || validate.timestamp <= new Date())
    {
        return createError({
            statusCode: 400,
            message: 'Le lien a expiré',
        });
    }

    db.delete(emailValidationTable).where(lte(emailValidationTable.timestamp, new Date())).run();
    const result = db.select({ state: usersTable.state }).from(usersTable).where(eq(usersTable.id, query.data.u)).get();

    if(result === undefined)
    {
        return createError({
            statusCode: 400,
            message: 'Aucune donnée utilisateur trouvée',
        });
    }
    if(result?.state === 1)
    {
        return createError({
            statusCode: 400,
            message: 'Votre compte a déjà été validé',
        });
    }

    db.update(usersTable).set({ state: 1 }).where(eq(usersTable.id, query.data.u)).run();

    sendRedirect(e, '/user/mailvalidated');
})