import type { User } from "better-auth";
import { DrizzleQueryError } from "drizzle-orm";
import { auth } from "../../../../pkg/auth/auth.js";
import { tryCatch } from "../../../../pkg/utils/tryCatch.js";

export type NewUser = {
	email: string;
	password: string;
	username: string;
	statusCode: number;
	message: string;
};

export const createNewUser = async (userData: NewUser) => {
	const { data, error } = await tryCatch(
		auth.api.createUser({
			body: {
				email: userData.email, // required
				password: userData.password, // required
				name: userData.username, // required
				role: "user",
				data: { username: userData.username },
			},
		}),
	);

	if (error) {
		if (error instanceof DrizzleQueryError) {
			// @ts-ignore
			if (error?.cause.message.includes("unique constraint")) {
				return {
					statusCode: 400,
					message: `${userData.username} already exists`,
				};
			}
		}

		return error;
	}

	return data;
};
