import { fetchApiTemplate } from "@/utils/templates/api";
import {
  makeBaasPostmanSchemaTemplate,
  makePostmanCollection,
} from "./makePostman";
import { slugify } from "@/utils/utils";
import WireframeSDK from "@/utils/WireframeSDK";
import { fetchLambdaEndpoint, lambdas } from "@/utils/templates/api/lambda";
import lambdaAPIShell from "@/utils/templates/api/lambdaAPIShell";
import { setLoading, showToast } from "@/context/Global";
import { tokenExpireError } from "@/context/Auth";
import Frame from "@/utils/templates/api/Frame";

export const makeLambdaEndpoints = async (
  endpoints,
  project,
  globalDispatch,
  authDispatch
) => {
  try {
    setLoading(globalDispatch, true, "commitRepo");

    const wSdk = new WireframeSDK();
    // const handleCommitToRepo = async (e) => {
    // e.target.innerHTML = "Commiting";
    let commitContent = "";
    let files = [];
    let customEndpoints = endpoints
      .filter((e) => e.type !== "default")
      .filter((e) => e.type !== "lambda");

    // return setLoading(globalDispatch, false, "commitRepo");
    lambdas.forEach((lambda) => {
      let lambdaEndpoints = endpoints.filter((e) => e.group === lambda);
      if (lambdaEndpoints.length === 0) return;

      let lambdaImports = fetchLambdaEndpoint(lambda)?.imports ?? "";
      let lambdaCommitContent = ``;
      lambdaEndpoints.forEach((endpoint) => {
        lambdaCommitContent += `
              
            //Endpoint
            /*
            ${typeof endpoint.code !== "undefined" ? endpoint.code : ""}
            */
    
            `;
      });

      lambdaCommitContent = lambdaAPIShell(lambdaCommitContent, lambdaImports);

      files.push({
        path: `lambda/${lambda}.js`,
        content: btoa(lambdaCommitContent),
      });
    });

    customEndpoints.forEach((endpoint) => {
      // console.log("customEndpoints >>", customEndpoints);
      commitContent += `
        //Description
        /*
        ${typeof endpoint.doc !== "undefined" ? endpoint.doc : ""}
        */
  
        //Endpoint
        ${typeof endpoint.code !== "undefined" ? endpoint.code : ""}
        
      `;
    });

    commitContent = Frame(
      commitContent,
      makeBaasPostmanSchemaTemplate(customEndpoints)
    );
    let postmanCollection = makePostmanCollection(customEndpoints, project);

    files.push({
      path: `${project.slug}PostmanCollection.json`,
      content: btoa(postmanCollection),
    });
    console.log("commitContent :>> ", commitContent);
    files.push({
      path: `${project.slug}.js`,
      content: btoa(commitContent),
    });

    files.push({
      path: "index.js",
      content: btoa(fetchApiTemplate("index.js")),
    });

    files.push({
      path: "health.js",
      content: btoa(fetchApiTemplate("health.js")),
    });

    customEndpoints.forEach((endpoint) => {
      files.push({
        path: `test/${slugify(endpoint.name)}.test.js`,
        content: btoa(endpoint.unit),
      });
    });

    const branch = prompt("Enter branch to commit");
    let res = await wSdk.commitFilesToRepo(
      project.slug,
      `${project.slug}_backend`,
      files,
      true,
      branch
    );
    if (!res.error) {
      showToast(globalDispatch, "Done", 3000, "success");
    }
    showToast(globalDispatch, "Commited to repo", 5000, "success");
    setLoading(globalDispatch, false, "commitRepo");
  } catch (error) {
    console.log("error :>> ", error);
    showToast(globalDispatch, "Error Commiting to repo", 5000, "error");
    setLoading(globalDispatch, false, "commitRepo");
    const message = error?.response?.data?.message
      ? error?.response?.data?.message
      : error?.message;

    tokenExpireError(authDispatch, message);
  }
};
