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 plant = req.query.plant;

	const conditions = [];

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

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

	const { data, error } = await tryCatch(
		db
			.select()
			.from(forklifts)
			//.innerJoin(forkliftCompanies, eq(forkliftCompanies.id, leases.companyId))
			.where(and(...conditions))
			.orderBy(asc(forklifts.serialNumber)),
	);

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

export default router;
