import axios from "axios";
import { eq, sql } from "drizzle-orm";
import type { Request, Response } from "express";
import { Router } from "express";
import https from "https";
import { db } from "../../../../pkg/db/db.js";
import { forkliftCompanies } from "../../../../pkg/db/schema/forkliftLeaseCompanys.js";
import { leases } from "../../../../pkg/db/schema/forkliftLeases.js";
import { serverData } from "../../../../pkg/db/schema/servers.js";
import { createLogger } from "../../../../pkg/logger/logger.js";
import { tryCatch } from "../../../../pkg/utils/tryCatch.js";

const router = Router();

router.patch("/:id", async (req: Request, res: Response) => {
	const log = createLogger({
		module: "forklifts",
		subModule: "update leases",
	});

	// when a server is updated and is posted from localhost or 127.0.0.1 we also want to post it to the test server so we can see it from there, we want to insert with update on conflict.
	const id = req.params.id;
	const updates: Record<string, any> = {};
	console.log(req.body);
	if (req.body?.leaseNumber !== undefined) {
		updates.leaseNumber = req.body.leaseNumber;
	}

	if (req.body?.startDate !== undefined) {
		updates.startDate = req.body.startDate;
	}

	if (req.body?.endDate !== undefined) {
		updates.endDate = req.body.endDate;
	}

	if (req.body?.companyId !== undefined) {
		updates.companyId = req.body.companyId;
	}

	if (req.body?.leaseLink !== undefined) {
		updates.leaseLink = req.body.leaseLink;
	}

	updates.upd_user = req.user!.username || "lst_user";
	updates.upd_date = sql`NOW()`;

	console.log(updates);
	try {
		if (Object.keys(updates).length > 0) {
			await db.update(leases).set(updates).where(eq(leases.id, id));
		}

		// if (req.hostname === "localhost" && process.env.MAIN_SERVER) {
		// 	log.info({}, "Running in dev server about to add in a new server");
		// 	const axiosInstance = axios.create({
		// 		httpsAgent: new https.Agent({ rejectUnauthorized: false }),
		// 		baseURL: process.env.MAIN_SERVER,
		// 		withCredentials: true,
		// 	});

		// 	const loginRes = (await axiosInstance.post(
		// 		`${process.env.MAIN_SERVER}/lst/api/auth/sign-in/username`,
		// 		{
		// 			username: process.env.MAIN_SERVER_USERNAME,
		// 			password: process.env.MAIN_SERVER_PASSWORD,
		// 		},
		// 		{
		// 			headers: { "Content-Type": "application/json" },
		// 		},
		// 	)) as any;

		// 	const setCookie = loginRes?.headers["set-cookie"][0];

		// 	//console.log(setCookie.split(";")[0].replace("__Secure-", ""));

		// 	if (!setCookie) {
		// 		throw new Error("Did not receive a Set-Cookie header from login");
		// 	}

		// 	const { data, error } = await tryCatch(
		// 		axios.patch(
		// 			`${process.env.MAIN_SERVER}/lst/api/forklifts/leases/${id}`,
		// 			updates,
		// 			{
		// 				headers: {
		// 					"Content-Type": "application/json",
		// 					Cookie: setCookie.split(";")[0],
		// 				},
		// 				withCredentials: true,
		// 			},
		// 		),
		// 	);

		// 	if (error) {
		// 		//console.log(error);
		// 		log.error(
		// 			{ stack: error },
		// 			"There was an error updating the lease to Main Server",
		// 		);
		// 	}
		// 	log.info(
		// 		{ stack: data?.data },
		// 		"A new lease was just updated to the server.",
		// 	);
		// }
		res.status(200).json({ message: `${id} was just updated` });
	} catch (error) {
		//console.log(error);
		res.status(200).json({ message: "Error updating lease", error });
	}
});

export default router;
