/**
 * 1. Get the silo adjustments from lstv1
 * 2. Build the new data set to match the new system
 * 3. insert the new values
 */

import axios from "axios";
import { db } from "../../../../../database/dbclient.js";
import { siloAdjustments } from "../../../../../database/schema/siloAdjustments.js";
import { createLog } from "../../../logger/logger.js";
import { delay } from "../../../../globalUtils/delay.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { settings } from "../../../../../database/schema/settings.js";
import { eq } from "drizzle-orm";
import {
    getSettings,
    serverSettings,
} from "../../../server/controller/settings/getSettings.js";

export const migrateAdjustments = async () => {
    /**
     * Migrates the silo adjustments from v1 to v2
     */

    //const { data, error } = await tryCatch(db.select().from(settings));
    // const { data, error } = await tryCatch(getSettings());

    // if (error) {
    //     createLog("error", "silo", "logistics", "Getting settings.");
    //     return;
    // }

    const data = serverSettings.length === 0 ? [] : serverSettings;

    const migrationCompleted = data?.filter(
        (n) => n.name === "siloAdjMigrations"
    );
    const server = data?.filter((n) => n.name === "v1SysServer");
    const port = data?.filter((n) => n.name === "v1SysPort");
    createLog("info", "silo", "logistics", "Getting v1 silo data.");

    if (migrationCompleted[0]?.value === "1") {
        createLog(
            "info",
            "silo",
            "logistics",
            "Migrations have already been completed on this server."
        );

        return;
    }
    const { data: s, error: siloError } = await tryCatch(
        axios.get(
            `http://${server[0]?.value}:${port[0]?.value}/api/v1/warehouse/getSilosAdjustment?startDate=1/1/2020&endDate=4/1/2026`
        )
    );

    if (siloError) {
        createLog("error", "silo", "logistics", "Getting settings.");
        return;
    }

    /**
     * Migrate all the silo adjustments :D
     */
    const silo: any = s?.data.data;
    createLog("info", "silo", "logistics", "Starting migration.");
    for (let i = 0; i < silo.length; i++) {
        const migrate = await db.insert(siloAdjustments).values({
            warehouseID: silo[i].warehouseID,
            locationID: silo[i].locationID,
            currentStockLevel: silo[i].currentStockLevel,
            newLevel: silo[i].newLevel,
            dateAdjusted: new Date(silo[i].dateAdjusted),
            lastDateAdjusted: new Date(silo[i].lastDateAdjusted),
            add_user: silo[i].add_user,
        });
        createLog(
            "info",
            "silo",
            "logistics",
            `Migrations for Date ${silo[0].dateAdjusted} on silo: ${silo[0].locationID}`
        );
        await delay(120);
    }

    /**
     * change the migration setting to be completed
     */

    await db
        .update(settings)
        .set({ value: "1" })
        .where(eq(settings.name, "siloAdjMigrations"));
    createLog("info", "silo", "logistics", "Migration completed.");
};
