import { prisma, BADGES } from "@repo/db";

export interface OldUser {
	firstname: string;
	publicId: string;
	badges: string[];
	lastname: string;
	email: string;
	password: string;
	permissions: {
		permissionList: string[];
	};
	settings: {
		privacyHideLastnameInNickname?: boolean;
		notifyRoomID?: string;
	};
	discord?: {
		profile: {
			id: string;
			username: string;
			global_name: string;
			avatar: string;
			email: string;
			verified: boolean;
		};
		tokens: {
			refresh_token: string;
			scope: string;
		};
	};
}

export const createNewUserFromOld = async (oldUser: OldUser) => {
	const existingPublicId = await prisma.user.findFirst({
		where: {
			publicId: oldUser.publicId,
		},
	});

	let varPublicId = oldUser.publicId;

	if (existingPublicId) {
		const lastUserPublicId = await prisma.user.findFirst({
			select: {
				publicId: true,
			},
			orderBy: {
				publicId: "desc",
			},
		});
		if (lastUserPublicId) {
			const lastUserInt = parseInt(lastUserPublicId.publicId.replace("VAR", ""));
			varPublicId = `VAR${(lastUserInt + 1).toString().padStart(4, "0")}`;
		}
	}

	const newUser = await prisma.user.create({
		data: {
			email: oldUser.email,
			password: oldUser.password,
			migratedFromV1: true,
			firstname: oldUser.firstname,
			lastname: oldUser.lastname,
			publicId: varPublicId,
			badges: [
				...oldUser.badges
					.map((badge) => {
						switch (badge) {
							case "day-1-member":
								return BADGES.DAY1;
							case "d-1":
								return BADGES.D1;
							case "p-1":
								return BADGES.P1;
							default:
								return null;
						}
					})
					.filter((badge) => badge !== null),
				BADGES.V1Veteran,
				...(oldUser.permissions.permissionList.includes("connect-dispatch") &&
				!oldUser.badges.includes("d-1")
					? [BADGES.D1]
					: []),
			],
		},
	});
	if (oldUser.discord) {
		await prisma.discordAccount.create({
			data: {
				tokenType: "Bearer",
				refreshToken: oldUser.discord.tokens.refresh_token,
				discordId: oldUser.discord.profile.id,
				userId: newUser.id,
				username: oldUser.discord.profile.username,
				globalName: oldUser.discord.profile.global_name,
				avatar: oldUser.discord.profile.avatar,
				email: oldUser.discord.profile.email,
				verified: oldUser.discord.profile.verified,
			},
		});
	}
	return newUser;
};
