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

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

const bodySchema = z.object({
    password: z.string(),
});

export default defineEventHandler(async (e) => {
    try
    {
        const query = await getValidatedQuery(e, querySchema.safeParse);
        
        if(!query.success)
            throw query.error;
    
        if(Bun.hash('2' + query.data.u.toString(), query.data.t).toString() !== query.data.h)
        {
            return createError({
                statusCode: 400,
                message: 'Requete incorrecte',
            });
        }
        if(Date.now() > query.data.t + (60 * 60 * 1000))
        {
            return createError({
                statusCode: 400,
                message: 'La requete a expirée',
            });
        }

        const body = await readValidatedBody(e, bodySchema.safeParse);

        if(!body.success)
            throw body.error;
    
        const db = useDatabase();
        db.delete(emailValidationTable).where(lte(emailValidationTable.timestamp, new Date())).run();
        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: 'La requete a expirée',
            });
        }
    
        db.delete(emailValidationTable).where(eq(emailValidationTable.id, query.data.i)).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',
            });
        }
    
        db.update(usersTable).set({ hash: await Bun.password.hash(body.data.password) }).where(eq(usersTable.id, query.data.u)).run();
    
        return { success: true };
    }
    catch(err: any)
    {
        console.error(err);
        
        return { success: false, error: err as Error };
    }
});