import axios from "axios";
import { eq, sql } from "drizzle-orm";
import type { Request, Response } from "express";
import { Router } from "express";
import https from "https";
import { db } from "../../../../pkg/db/db.js";
import { serverData } from "../../../../pkg/db/schema/servers.js";
import { settings } from "../../../../pkg/db/schema/settings.js";
import { createLogger } from "../../../../pkg/logger/logger.js";
import { tryCatch } from "../../../../pkg/utils/tryCatch.js";

const router = Router();

router.patch("/:id", async (req: Request, res: Response) => {
	const log = createLogger({ module: "admin", subModule: "update setting" });

	// when a server is updated and is posted from localhost or 127.0.0.1 we also want to post it to the test server so we can see it from there, we want to insert with update on conflict.
	const id = req.params.id;
	const updates: Record<string, any> = {};

	if (req.body?.name !== undefined) {
		updates.name = req.body.name;
	}
	if (req.body?.value !== undefined) {
		updates.value = req.body.value;
	}
	if (req.body?.description !== undefined) {
		updates.description = req.body.description;
	}

	if (req.body?.moduleName !== undefined) {
		updates.moduleName = req.body.moduleName;
	}

	updates.upd_user = req.user!.username || "lst_user";
	updates.upd_date = sql`NOW()`;

	try {
		if (Object.keys(updates).length > 0) {
			await db
				.update(settings)
				.set(updates)
				.where(eq(settings.settings_id, id));
		}

		res.status(200).json({ message: `Setting was just updated` });
	} catch (error) {
		console.log(error);
		res.status(400).json({ message: "Error Server updated", error });
	}
});

export default router;
