import { Router, type Request, type Response } from "express";

import { authClient } from "../../../pkg/auth/auth-client.js";
import z from "zod";
import { auth } from "../../../pkg/auth/auth.js";

const resetSchema = z.object({
    email: z.string(),
});

const router = Router();

router.post("/", async (req: Request, res: Response) => {
    try {
        const validated = resetSchema.parse(req.body);

        const data = await auth.api.requestPasswordReset({
            body: {
                email: validated.email,
                redirectTo: `${process.env.BETTER_AUTH_URL}/user/resetpassword`,
            },
        });
        return res.json(data);
    } catch (err) {
        if (err instanceof z.ZodError) {
            const flattened = z.flattenError(err);
            return res.status(400).json({
                error: "Validation failed",
                details: flattened,
            });
        }

        console.log(err);
        return res.status(400).json({ error: err });
    }
});

export default router;
