import { and, count, eq } from 'drizzle-orm';
import { z } from 'zod';
import { usersTable } from '~/db/schema';
import { schema as registration } from '~/schemas/registration';
import useDatabase from '~/composables/useDatabase';

const schema = z.object({
    newPassword: registration.shape.password,
    oldPassword: registration.shape.password,
});

export default defineEventHandler(async (e) => {
    try
    {
        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 body = await readValidatedBody(e, schema.safeParse);
        
        if(!body.success)
            throw body.error;
        
        const db = useDatabase();
        const check = db.select({ hash: usersTable.hash }).from(usersTable).where(eq(usersTable.id, session.user.id)).get();

        if(!check || !check.hash)
        {
            return createError({
                statusCode: 401,
                message: 'Unauthorized',
            });
        }
        if(!await Bun.password.verify(body.data.oldPassword, check.hash))
        {
            return { success: false, error: "Ancien mot de passe incorrect" };
        }

        db.update(usersTable).set({ hash: await Bun.password.hash(body.data.newPassword) }).where(eq(usersTable.id, session.user.id)).run();

        return { success: true };
    }
    catch(err: any)
    {
        console.error(err);
        
        return createError({
            statusCode: 500,
        });
    }
});