import { eq } from "drizzle-orm";
import { Router } from "express";
import { db } from "../db/db.controller.js";
import { scanUser } from "../db/schema/scanUsers.js";
import { settings } from "../db/schema/settings.schema.js";
import { apiReturn } from "../utils/returnHelper.utils.js";

const r = Router();

// scanners that are dedicated to specific users.
const SPECIAL_SCANNERS = [98];

const buildAllowedScannerIds = (scannerCount: number) => {
	const generatedIds = Array.from({ length: scannerCount }, (_, i) => i + 1);

	return Array.from(new Set([...generatedIds, ...SPECIAL_SCANNERS])).sort(
		(a, b) => a - b,
	);
};

r.get("/", async (_, res) => {
	// get the scan users and setting
	const scanusers = await db.select().from(scanUser);
	const scannerIdSetting = await db
		.select()
		.from(settings)
		.where(eq(settings.name, "scannerIds"));

	const usedScannerIds = scanusers.map((x) => Number(x.scannerId));
	const allowedScannerIds = buildAllowedScannerIds(
		Number(scannerIdSetting[0]?.value ?? 0),
	);

	const availableScannerIds = allowedScannerIds.filter(
		(id) => !usedScannerIds.includes(id),
	);

	const data = availableScannerIds.map((id) => ({
		label: `${id}`,
		value: id,
	}));

	return apiReturn(res, {
		success: true,
		level: "info",
		module: "mobile",
		subModule: "scanner",
		message: `There are ${availableScannerIds.length} scanner id's`,
		data,
		status: 200,
	});
});

export default r;
