"use server";
import NextCrypto from "next-crypto";
import { redirect } from "next/navigation";

const nextCrypto = new NextCrypto(
  "2f3c097b29fc4a70084403ad7b2f9def1ba0bf6e96c892457b0bebd15d3f48fd7396120708cb7efdf7f4b09003701710c0904addaaf991d412403b47d9762aa9"
);

export async function defaultPagination() {
  const paginate = await encryptQuery({
    size: 10,
    page: 1,
    orderBy: "uu_id",
    orderType: "desc",
    query: {},
  });
  return paginate.replaceAll(" ", "+");
}

export async function decryptQuery(query: string) {
  if (!query) return {};
  const decryptURL = await nextCrypto.decrypt(String(query.replace(/ /g, "+")));
  try {
    const cleanedString = String(decryptURL).replace(/\\/g, "");
    const decodedString = decodeURI(cleanedString || "{}");
    const parsedObject = JSON.parse(decodedString);
    if (typeof parsedObject !== "object") {
      return JSON.parse(parsedObject);
    }
    return parsedObject;
  } catch (error) {
    return {};
  }
}

export async function encryptQuery(queryObject: any) {
  const encodedURL = encodeURI(JSON.stringify(queryObject));
  return (await nextCrypto.encrypt(encodedURL)).replaceAll(";", "%3B");
}

export async function handleFormSubmission(formData: FormData): Promise<void> {
  let inputs: any = {};
  formData.forEach((value, key) => {
    if (key.includes("page")) {
      inputs.page = value;
    } else if (key.includes("size")) {
      inputs.size = value;
    } else if (key.includes("orderBy")) {
      inputs.orderBy = value;
    } else if (key.includes("orderType")) {
      inputs.orderType = value;
    } else if (key.includes("section")) {
    } else if (key.includes("ACTION_ID")) {
    } else {
      if (value) {
        inputs.query = {
          ...inputs.query,
          [key]: value,
        };
      }
    }
  });
  const queryEncrypt = await encryptQuery(inputs);
  redirect(
    `/${formData.get("section")}?q=${queryEncrypt.replaceAll(" ", "+")}`
  );
}

export async function handleCreateSubmission({
  section,
  data,
}: {
  section: string;
  data: any;
}) {
  const queryEncrypt = await encryptQuery(data);
  redirect(`/${section}/create?q=${queryEncrypt.replaceAll(" ", "+")}`);
}

export async function handleUpdateSubmission({
  section,
  data,
}: {
  section: string;
  data: any;
}) {
  const queryEncrypt = await encryptQuery(data);
  
}
