import { hash } from 'bun';
import { eq, or } from 'drizzle-orm';
import { z } from 'zod';
import useDatabase from '~/composables/useDatabase';
import { usersTable } from '~/db/schema';

const schema = z.object({
    profile: z.string(),
});

export default defineEventHandler(async (e) => {
    try
    {
        const db = useDatabase();
        const body = await readValidatedBody(e, schema.safeParse);

        if (!body.success)
        {
            setResponseStatus(e, 406);
            return { success: false, error: body.error };
        }

        const result = db.select({ id: usersTable.id, email: usersTable.email, username: usersTable.username, hash: usersTable.hash }).from(usersTable).where(or(eq(usersTable.email, body.data.profile), eq(usersTable.username, body.data.profile))).get();

        if(result && result.id)
        {
            const id = hash('reset' + result.id + result.hash, Date.now());
            const timestamp = Date.now() + 1000 * 60 * 60;
            await runTask('validation', {
                payload: {
                    type: 'validation',
                    id, timestamp,
                }
            });
            await runTask('mail', {
                payload: {
                    type: 'mail',
                    data: {
                        id, timestamp,
                        userId: result.id,
                        username: result.username,
                    },
                    template: 'reset-password',
                    to: [result.email],
                }
            });
        }
    }
    catch(err: any)
    {
        console.error(err);
        
        return { success: false, error: err as Error };
    }
});