"use server";

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

export const checkEmailCode = async (code: string) => {
	const users = await prisma.user.findMany({
		where: {
			emailVerificationToken: code,
		},
		select: {
			id: true,
			emailVerificationToken: true,
			emailVerificationExpiresAt: true,
		},
	});
	const user = users[0];

	if (!user || !user.emailVerificationExpiresAt) {
		return { error: "Code ist ungültig" };
	}

	if (user.emailVerificationExpiresAt < new Date()) {
		return { error: "Code ist nicht mehr gültig" };
	}

	await prisma.user.update({
		where: {
			id: user.id,
		},
		data: {
			emailVerified: true,
			emailVerificationToken: null,
			emailVerificationExpiresAt: null,
		},
	});
	return {
		message: "Email bestätigt!",
	};
};
