import { NextApiRequest, NextApiResponse } from "next";
import { PrismaClient } from "@prisma/client";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";

const prisma = new PrismaClient()
const SECRET_KEY = process.env.JWT_SECRET as string;


export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" });

    const { email, password } = req.body;

    const existingUser = await prisma.user.findUnique({ where: { email } });
    if (existingUser) return res.status(400).json({ message: "User already exists" });

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

    const token = jwt.sign({ email: user.email }, SECRET_KEY, { expiresIn: "1d" });

    res.setHeader("Set-Cookie", `token=${token}; HttpOnly; Path=/; Secure`);
    res.status(201).json({ message: "User registered", user, token });
}
