import { and, asc, eq, relations } from "drizzle-orm";
import type { Request, Response } from "express";
import { Router } from "express";
import { db } from "../../../../pkg/db/db.js";
import { forkliftCompanies } from "../../../../pkg/db/schema/forkliftLeaseCompanys.js";
import { leases } from "../../../../pkg/db/schema/forkliftLeases.js";
import { forklifts } from "../../../../pkg/db/schema/forklifts.js";
import { leaseInvoices } from "../../../../pkg/db/schema/leaseInvoices.js";
import { tryCatch } from "../../../../pkg/utils/tryCatch.js";

const router = Router();

router.get("/", async (req: Request, res: Response) => {
	const invoiceNumber = req.query.lease;

	const conditions = [];

	if (invoiceNumber !== undefined) {
		conditions.push(eq(leaseInvoices.invoiceNumber, `${invoiceNumber}`));
	}

	//conditions.push(eq(forkliftCompanies.active, true));

	const { data, error } = await tryCatch(
		db
			.select(
				// 	{
				// 	id: leases.id,
				// 	leaseNumber: leases.leaseNumber,
				// 	startDate: leases.startDate,
				// 	endDate: leases.endDate,
				// 	leaseLink: leases.leaseLink,
				// 	companyName: forkliftCompanies.name,
				// 	add_user: leases.add_user,
				// 	add_date: leases.add_date,
				// 	upd_user: leases.upd_user,
				// 	upd_date: leases.upd_date,
				// }
			)
			.from(leaseInvoices)
			//.innerJoin(forkliftCompanies, eq(forkliftCompanies.id, leases.companyId))
			.where(and(...conditions))
			.orderBy(asc(leaseInvoices.invoiceNumber)),
	);

	if (error) {
		return res.status(400).json({ error: error });
	}
	res.status(200).json({ message: "Current Leases", data: data });
});

export default router;
