import { and, asc, eq } 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 { tryCatch } from "../../../../pkg/utils/tryCatch.js";

const router = Router();

router.get("/", async (req: Request, res: Response) => {
	const conditions = [];

	if (req.query.lease !== undefined) {
		conditions.push(eq(leases.leaseNumber, `${req.query.lease}`));
	}

	if (req.query.companyId !== undefined) {
		conditions.push(eq(leases.companyId, `${req.query.companyId}`));
	}

	//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(leases)
			.innerJoin(forkliftCompanies, eq(forkliftCompanies.id, leases.companyId))
			.where(and(...conditions))
			.orderBy(asc(leases.leaseNumber)),
	)) as any;

	// add the forklifts that are in this lease
	const forkliftData = await db.select().from(forklifts);

	if (error) {
		return res.status(400).json({ error: error });
	}

	const leaseData = data.map((i: any) => ({
		...i,
		forklifts: forkliftData.filter((x) => x.leaseId === i.id),
	}));
	res.status(200).json({ message: "Current Leases", data: leaseData });
});

export default router;
