import { Client } from "pg";
import { createLogger } from "../../../pkg/logger/logger.js";

export const addListeners = async () => {
	const log = createLogger({ module: "utils", subModule: "listeners" });
	const client = new Client({
		connectionString: process.env.DATABASE_URL_V1,
	});

	await client.connect();

	try {
		log.info({}, "Running the new log listener");
		await client.query(`
        CREATE OR REPLACE FUNCTION notify_new_log()
        RETURNS trigger AS $$
        BEGIN
        PERFORM pg_notify('logs_channel', row_to_json(NEW)::text);
        RETURN NEW;
        END;
        $$ LANGUAGE plpgsql;

        CREATE TRIGGER logs_notify_trigger
        AFTER INSERT ON logs
        FOR EACH ROW
        EXECUTE FUNCTION notify_new_log();
    `);
	} catch (e) {
		log.info({}, "log listener exist");
	}

	try {
		log.info({}, "Running the new label listener");
		await client.query(`
        CREATE OR REPLACE FUNCTION notify_new_label()
        RETURNS trigger AS $$
        BEGIN
        PERFORM pg_notify('label_channel', row_to_json(NEW)::text);
        RETURN NEW;
        END;
        $$ LANGUAGE plpgsql;

        CREATE TRIGGER label_notify_trigger
        AFTER INSERT ON prodlabels
        FOR EACH ROW
        EXECUTE FUNCTION notify_new_label();
    `);
	} catch (e) {
		log.info({}, "label listener exists");
	}

	try {
		log.info({}, "Bad data removing bad history data");
		await client.query(`
        DELETE FROM public."invHistoricalData" 
        WHERE upd_user = 'LST'
    `);
	} catch (e) {
		log.info({}, "Error deleting bad inv data");
	}
};

export const manualFixes = async () => {
	const fixQuery = `ALTER TABLE "serverData" ADD CONSTRAINT "serverData_name_unique" UNIQUE("name");`;

	const log = createLogger({ module: "utils", subModule: "manual fixes" });
	const client = new Client({
		connectionString: `postgresql://${process.env.DATABASE_USER}:${process.env.DATABASE_PASSWORD}@${process.env.DATABASE_HOST}:${process.env.DATABASE_PORT}/${process.env.DATABASE_DB}`,
	});

	await client.connect();

	try {
		log.info({}, "Running the manual fix");
		await client.query(fixQuery);
	} catch (e) {
		log.info({ error: e }, "Fix was not completed");
	}
};
