import { sql } from "drizzle-orm";
import { readFileSync } from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { db } from "../../../../pkg/db/db.js";
import { modules } from "../../../../pkg/db/schema/modules.js";
import { createLogger } from "../../../../pkg/logger/logger.js";
import { tryCatch } from "../../../../pkg/utils/tryCatch.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export const baseModules = async () => {
	const log = createLogger({ module: "system", subModule: "base modules" });
	const modulePath = path.resolve(__dirname, "./modules.json");
	const newModules = JSON.parse(readFileSync(modulePath, "utf-8"));

	for (const m of newModules) {
		const { data, error } = await tryCatch(
			db
				.insert(modules)
				.values(m)
				.onConflictDoUpdate({
					target: modules.name,
					set: {
						category: m.category,
						link: m.link,
						icon: m.icon,
						roles: m.roles,
						upd_date: sql`NOW()`,
						upd_user: "LST-user",
					},
				})
				.returning({ name: modules.name }),
		);

		if (error) {
			console.log(error);
			log.error({ error }, "There was an error adding new settings");
		}

		if (data) {
			//log.info({ newModulesAdded: data }, "New settings added");
		}
	}
};
