import axios from "axios";
import { db } from "../../../../database/dbclient.js";
import { prodPermissions } from "../../../../database/schema/prodPermissions.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { query } from "../../sqlServer/prodSqlServer.js";
import { userCheck } from "../../sqlServer/querys/prodUser/usercheck.js";
import { prodEndpointCreation } from "../../../globalUtils/createUrl.js";

export const prodUser = async (data: any) => {
    // get the prodPermissions so we can make sure we have one in here
    const { data: prodPerm, error: pe } = await tryCatch(
        db.select().from(prodPermissions)
    );

    // create url
    const grantUrl = await prodEndpointCreation(
        `/public/v1.0/Administration/User/${data.username}/Grant`
    );

    const newurl = await prodEndpointCreation(
        `/public/v1.0/Administration/User`
    );

    const revoke = await prodEndpointCreation(
        `/public/v1.0/Administration/User/${data.username}/Revoke`
    );

    if (pe) {
        console.log(pe);
        return {
            success: false,
            message: "There was an error getting the base prod permissions",
            data: pe,
        };
    }

    // check if we sent over a valid permissions fole over
    const permRoleCheck = prodPerm.filter((n: any) => n.name === data.role);

    if (permRoleCheck.length === 0) {
        return {
            success: false,
            message: `Role: ${data.role}, dose note exist please check the role you have selected and try again.`,
            data: [],
        };
    }

    // dose this user already exist?
    const quc = userCheck.replace("[userName]", data.username);
    const { data: usercheck, error: userError } = (await tryCatch(
        query(quc, "Checks for existing user")
    )) as any;

    if (userError) {
        console.log(userError);
    }

    //console.log(permRoleCheck);

    if (usercheck?.data.length === 0) {
        // create the user
        const newUser: any = {
            userId: data.username,
            remark: data.remark,
            languageCode: "en",
            active: true,
            roles: permRoleCheck[0].roles,
            rolesLegacy: permRoleCheck[0].rolesLegacy,
        };

        const { data: newU, error: newE } = (await tryCatch(
            axios.post(newurl, newUser, {
                headers: {
                    "X-API-Key": process.env.TEC_API_KEY || "",
                    "Content-Type": "application/json",
                },
            })
        )) as any;

        if (newE) {
            console.log(newE);
            return {
                success: false,
                message: `${data.username} encountered an error creating..`,
                data: newE.response.data,
            };
        }

        return {
            success: true,
            message: `${data.username} was just created or updated.`,
            data: [],
        };
    } else {
        // revoke and readd
        const revokePerms: any = {
            roles: JSON.parse(
                usercheck.data[0].roles.replaceAll("\\", "\\\\")
            ) || ["Manufacturing\\IssueMaterial\\MaterialHandler"],
            rolesLegacy: JSON.parse(usercheck.data[0].legacyRoles) || [3],
        };

        const { data: newU, error: newE } = (await tryCatch(
            axios.patch(revoke, revokePerms, {
                headers: {
                    "X-API-Key": process.env.TEC_API_KEY || "",
                    "Content-Type": "application/json",
                },
            })
        )) as any;

        if (newE) {
            console.log("Revoke failed with: ", newE.response.data);

            return {
                success: false,
                message: `${data.username} encountered an error updating..`,
                data: newE.response.data,
            };
        }

        // add the new roles to the user.
        const grantRole: any = {
            roles: permRoleCheck[0].roles,
            rolesLegacy: permRoleCheck[0].rolesLegacy,
        };

        const { data: grant, error: grante } = (await tryCatch(
            axios.patch(grantUrl, grantRole, {
                headers: {
                    "X-API-Key": process.env.TEC_API_KEY || "",
                    "Content-Type": "application/json",
                },
            })
        )) as any;

        if (grante) {
            console.log(newE.response.data);
            return {
                success: false,
                message: `${data.username} encountered an error updating..`,
                data: newE.response.data,
            };
        }
    }

    return {
        success: true,
        message: `${data.username} was just created or updated.`,
        data: [],
    };
};

const deleteUser = async (data: any, permRoleCheck: any) => {
    const remove = await prodEndpointCreation(
        `/public/v1.0/Administration/User/${data.username}`
    );
    const newurl = await prodEndpointCreation(
        `/public/v1.0/Administration/User`
    );

    const { data: removal, error: grante } = (await tryCatch(
        axios.delete(remove, {
            headers: {
                "X-API-Key": process.env.TEC_API_KEY || "",
                "Content-Type": "application/json",
            },
        })
    )) as any;

    const newUser: any = {
        userId: data.username,
        remark: data.remark,
        languageCode: "en",
        active: true,
        roles: permRoleCheck[0].roles,
        rolesLegacy: permRoleCheck[0].rolesLegacy,
    };

    const { data: newU, error: newE } = (await tryCatch(
        axios.post(newurl, newUser, {
            headers: {
                "X-API-Key": process.env.TEC_API_KEY || "",
                "Content-Type": "application/json",
            },
        })
    )) as any;

    if (newE) {
        console.log(newE);
        return {
            success: false,
            message: `${data.username} encountered an error creating..`,
            data: newE.response.data,
        };
    }

    return {
        success: true,
        message: `${data.username} was just created.`,
        data: [],
    };
};
