import axios from "axios";
import { type DrizzleError, sql } from "drizzle-orm";
import type { Request, Response } from "express";
import { Router } from "express";
import https from "https";
import type z from "zod";
import { db } from "../../../../pkg/db/db.js";
import {
	leaseInvoiceForklifts,
	newForkliftInvoiceSchema,
} from "../../../../pkg/db/schema/forkliftLeasesInvoice.js";
import {
	leaseInvoices,
	newInvoiceSchema,
} from "../../../../pkg/db/schema/leaseInvoices.js";
import { createLogger } from "../../../../pkg/logger/logger.js";
import { tryCatch } from "../../../../pkg/utils/tryCatch.js";

const router = Router();

router.post("/", async (req: Request, res: Response) => {
	// when a new server 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
	//res.status(200).json({ message: "Server added", ip: req.hostname });
	const log = createLogger({ module: "forklift", subModule: "add invoice" });

	const parsedInvoice = newInvoiceSchema.safeParse({
		leaseId: req.body.leaseId,
		companyId: req.body.companyId,
		invoiceNumber: req.body.invoiceNumber,
		invoiceDate: req.body.invoiceDate,
		uploadedBy: req.body.uploadedBy,
		totalAmount: req.body.totalAmount,
	});

	if (!parsedInvoice.success)
		return res.status(400).json({ error: parsedInvoice.error.flatten });

	const invoiceData = parsedInvoice.data;

	const forkliftItems = Array.isArray(req.body.forklifts)
		? req.body.forklifts
		: [];

	const validatedForklifts = []; //z.infer<typeof newForkliftInvoiceSchema>[] = [];

	for (const item of forkliftItems) {
		// const parsedItem = newForkliftInvoiceSchema.safeParse(item);
		// if (parsedItem.success) {
		validatedForklifts.push(item);
		//} else {
		//return res.status(400).json({ error: parsedItem.error.flatten() });
		//}
	}

	// this will be the total invoice amount minus each forklift this way we can keep the total amount in here plus forklifts seperated
	// const totalAmount = (
	// 	validatedForklifts.reduce((sum, f) => sum + Number(f.amount || 0), 0) -
	// 	req.body.totalInvoice
	// ).toString();

	const { data, error } = await tryCatch(
		db
			.insert(leaseInvoices)
			.values({
				...invoiceData,
				add_date: sql`NOW()`,
				totalAmount: req.body.totalAmount,
				uploadedBy: req.user!.username || "lst_user",
			})
			// .onConflictDoUpdate({
			// 	target: leaseInvoices.invoiceNumber,
			// 	set: {
			// 		totalAmount,
			// 		invoiceDate: invoiceData.invoiceDate,
			// 		uploadedBy: req.user!.username || "lst_user",
			// 	},
			// })
			.returning(),
	);

	if (error) {
		const err: DrizzleError = error;
		return res.status(400).json({
			message: `Error adding lease`,
			// @ts-ignore
			error: err.cause.detail,
		});
	}

	const invoiceId = data[0]?.id;
	console.log(validatedForklifts);
	const forkliftInvoices = validatedForklifts.map((f) => {
		return {
			invoiceId,
			forkliftId: f.forklift_id,
			amount: f.amount,
		};
	});

	if (validatedForklifts.length > 0) {
		await db.insert(leaseInvoiceForklifts).values(forkliftInvoices);
		// .onConflictDoUpdate({
		//   target: [
		//     leaseInvoiceForklifts.invoiceId,
		//     leaseInvoiceForklifts.forkliftId,
		//   ],
		//   set: { amount: (excluded) => excluded.amount },
		// });
	}
	// 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, // e.g. "https://example.com"
	// 		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];

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

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

	// 	if (error) {
	// 		log.error(
	// 			{ stack: error },
	// 			"There was an error adding the company to Main Server",
	// 		);
	// 	}
	// 	log.info(
	// 		{ stack: data?.data },
	// 		"A new Company was just added to the server.",
	// 	);
	// }

	return res
		.status(201)
		.json({ message: `lease ${data[0]?.invoiceNumber} added`, data: data });
});

export default router;
