const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
require("dotenv").config();
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();

const generateJwtToken = (userId) => {
  return jwt.sign({ id: userId }, process.env.JWT_SECRET, { expiresIn: "5h" });
};

async function register(req, res) {
  const { fullnames, email, phone, password } = req.body;

  if (!fullnames || !email || !phone || !password) {
    return res.status(400).json({ error: "All fields are required" });
  }

  try {
    // Check for duplicates
    const existingUser = await prisma.user.findFirst({
      where: {
        OR: [{ email }, { phone }]
      }
    });

    if (existingUser) {
      return res.status(409).json({ error: "Email or phone already in use" });
    }

    const hashedPassword = await bcrypt.hash(password, 10);

    const newUser = await prisma.user.create({
      data: {
        fullnames,
        email,
        phone,
        roleId: 1,
        imageUrl: "https://static.vecteezy.com/system/resources/thumbnails/009/734/564/small_2x/default-avatar-profile-icon-of-social-media-user-vector.jpg",
        password: hashedPassword
      }
    });

    const token = generateJwtToken(newUser.id);
    res.cookie("jwt", token, { httpOnly: true, maxAge: 1000 * 60 * 60 * 2 });

    res.status(201).json({
      message: "User registered successfully",
      user: {
        id: newUser.id,
        fullnames: newUser.fullnames,
        email: newUser.email
      }
    });
  } catch (err) {
    console.error("❌ Registration error:", err.message);
    res.status(500).json({ error: "Internal Server Error" });
  }
}
module.exports = { register };