import { NextRequest, NextResponse } from "next/server";
import bcrypt from 'bcryptjs';
import prisma from "@/app/prisma";
import { z } from "zod/v4";

const schema = z.object({
    username: z.string().min(3, "Username must be at least 3 characters long").max(32, "Username must be at most 32 characters long"),
    name: z.string().min(3, "Name must be at least 3 characters long").max(32, "Name must be at most 32 characters long"),
    email: z.string().email("Invalid email address"),
    password: z.string().min(8, "Password must be at least 8 characters long").max(32, "Password must be at most 32 characters long").regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,32}$/, "Password must contain at least one lowercase letter, one uppercase letter, one digit, and one special character"),
});

export async function POST(request: NextRequest) {
    try {
        const body = schema.parse(await request.json());

        const user = await prisma.user.create({
            data: {
                username: body.username,
                name: body.name,
                email: body.email,
                password: await bcrypt.hash(body.password, 10),
            },
        });

        return NextResponse.json({ user }, { status: 201 });

    } catch (error: any) {
        if(error instanceof z.ZodError) {
            return NextResponse.json({ error: error.issues[0].message }, { status: 400 });
        }
        return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
    }
}
        