import prisma from "../prisma/client.js";
import {generateToken} from "../utils/jwt.js";
import {hashPassword, comparePassword} from "../utils/password.js";

/**
 * REGISTER
 * POST /api/auth/register
 */
export async function register(req, res) {
	const {username, password, role} = req.body;

	if (!username || !password) {
		return res.status(400).json({error: "Username and password required"});
	}

	const existingUser = await prisma.user.findUnique({
		where: {username},
	});

	if (existingUser) {
		return res.status(409).json({error: "Username already exists"});
	}

	const hashedPassword = await hashPassword(password);

	const user = await prisma.user.create({
		data: {
			username,
			password: hashedPassword,
			role: role || "admin",
		},
	});

	res.status(201).json({
		message: "User registered successfully",
		user: {
			id: user.id,
			username: user.username,
			role: user.role,
		},
	});
}

/**
 * LOGIN
 * POST /api/auth/login
 */
export async function login(req, res) {
	const {username, password} = req.body;

	if (!username || !password) {
		return res.status(400).json({error: "Username and password required"});
	}

	const user = await prisma.user.findUnique({
		where: {username},
	});

	if (!user) {
		return res.status(401).json({error: "Invalid credentials"});
	}

	const isValid = await comparePassword(password, user.password);

	if (!isValid) {
		return res.status(401).json({error: "Invalid credentials"});
	}

	const token = generateToken({
		userId: user.id,
		username: user.username,
		role: user.role,
	});

	res.json({token});
}
