import { fromNodeHeaders } from "better-auth/node";
import { differenceInDays } from "date-fns";
import { eq, sql } from "drizzle-orm";
import { type Request, type Response, Router } from "express";
import z from "zod";
import { auth } from "../../../pkg/auth/auth.js";
import { db } from "../../../pkg/db/db.js";
import { account, user } from "../../../pkg/db/schema/auth-schema.js";

const router = Router();

const signin = z.object({
	username: z.string(),
	password: z.string().min(8, "Password must be at least 8 characters"),
});

// GET /health
router.post("/", async (req: Request, res: Response) => {
	try {
		const validated = signin.parse(req.body);

		const userLogin = await db
			.select()
			.from(user)
			.where(eq(user.username, validated.username));

		if (
			!userLogin[0].lastLogin ||
			differenceInDays(userLogin[0].lastLogin, new Date(Date.now())) > 120
		) {
			// due to the new change we want to check if the user is alpla if alpla then we send a password reset if not an alpla email we need to change there password to the defined Alpla2025!

			if (userLogin[0].email.includes("@alpla.com")) {
				// send password reset email
				await auth.api.requestPasswordReset({
					body: {
						email: userLogin[0].email,
						redirectTo: `${process.env.BETTER_AUTH_URL}/user/resetpassword`,
					},
				});

				await db
					.update(user)
					.set({ lastLogin: sql`NOW()` })
					.where(eq(user.id, userLogin[0].id));

				return res.status(401).json({
					success: false,
					message: `${validated.username} it looks like you haven't been here in a while, you will need to change your password, an email was just sent to ${userLogin[0].email} with a link to reset your password.`,
					data: { user: userLogin[0].id },
				});
			} else {
				//reset the password so its updated to the new one
				await db
					.update(account)
					.set({
						password:
							"6ab221fdf322129ae48d808f6db3f592:f8e34a1e4e3c8133a54d8063e1d2b640d5e573cc53bd799cf78abfa2d2bfcc3c6cd84540e73e75d9da8faefad4ea31fe50a87a6f5773e421c082b5095a7b0491",
					})
					.where(eq(account.userId, userLogin[0].id));
				// change last login to now
				await db
					.update(user)
					.set({ lastLogin: sql`NOW()` })
					.where(eq(user.id, userLogin[0].id));
				return res.status(401).json({
					success: false,
					message: `${validated.username} dose not have a valid alpla email your password will be changed to  Alpla2025! it is recommended to login and change your password.`,
					data: [],
				});
			}
		}

		const logging = (await auth.api.signInUsername({
			body: {
				username: validated.username,
				password: validated.password,
			},
			asResponse: true,
		})) as any;

		logging.headers.forEach((value: string, key: string) => {
			if (key.toLowerCase() === "set-cookie") {
				res.append("set-cookie", value); // Express method
			} else {
				res.setHeader(key, value);
			}
		});
		const data = await logging.json();

		await db
			.update(user)
			.set({ lastLogin: sql`NOW()` })
			.where(eq(user.id, userLogin[0].id));

		return res.status(logging.status).json(data);
	} catch (error) {
		console.log(error);
		return res
			.status(500)
			.json({ message: "seem to have encountered an error please try again." });
	}
});

export default router;
