import { Router } from "express";
import type { Request, Response } from "express";
import z from "zod";
import { auth } from "../../../pkg/auth/auth.js";

const router = Router();

const registerSchema = z.object({
    email: z.email(),
    name: z.string().min(2).max(100),
    password: z.string().min(8, "Password must be at least 8 characters"),
    username: z
        .string()
        .min(3)
        .max(32)
        .regex(/^[a-zA-Z0-9_]+$/, "Only alphanumeric + underscores"),
    displayUsername: z.string().min(2).max(100).optional(), // optional in your API, but supported
});

router.post("/", async (req: Request, res: Response) => {
    try {
        // Parse + validate incoming JSON against Zod schema
        const validated = registerSchema.parse(req.body);

        // Call Better Auth signUp
        const user = await auth.api.signUpEmail({
            body: validated,
        });

        return res.status(201).json(user);
    } catch (err) {
        if (err instanceof z.ZodError) {
            const flattened = z.flattenError(err);
            return res.status(400).json({
                error: "Validation failed",
                details: flattened,
            });
        }
        console.error(err);
        return res.status(500).json({ error: "Internal server error" });
    }
});

export default router;
