import { eq, sql } from "drizzle-orm";
import { Router } from "express";
import { db } from "../db/db.controller.js";
import { scanLog } from "../db/schema/scanlog.schema.js";
import { scanUser } from "../db/schema/scanUsers.js";
import { emitToRoom } from "../socket.io/roomEmitter.socket.js";
import { apiReturn } from "../utils/returnHelper.utils.js";

const router = Router();

router.post("/", async (req, res) => {
	const body = req.body;
	try {
		await db
			.update(scanUser)
			.set({ lastScan: sql`NOW()` })
			.where(eq(scanUser.name, body.user));
	} catch (error) {
		console.log(error);
	}
	const newLog = await db
		.insert(scanLog)
		.values({
			scannerId: body.scannerId ?? "",
			message: body.message ?? "",
			prompt: body.prompt ?? "",
			commandDescription: body.commandDescription ?? "",
			status: body.status ?? "",
			lines: body.lines ?? "",
			user: body.user ?? "",
			runningNumber: body.runningNumber ?? "",
			scannerVersion: body.scannerVersion ?? "0",
		})
		.returning();

	emitToRoom(`scanLog`, newLog[0]);

	return apiReturn(res, {
		success: true,
		level: "info",
		module: "mobile",
		subModule: "scan logs",
		message: `New log from ${body.scannerId}`,
		data: newLog,
		status: 200,
	});
});

export default router;
