import { useState } from "react";
import { formatCode } from "@/utils/utils";

interface PostmanCollection {
  item: PostmanItem[];
}

interface PostmanItem {
  request?: {
    method: string;
    url: { raw: string };
    header?: { key: string; value: string }[];
    auth?: { type: string };
  };
  response?: { code: number; name: string; body: string }[];
  item?: PostmanItem[];
  name: string;
}

interface MkdPostmanItem {
  method: string;
  name: string;
  url: string;
  successBody: string;
  errors: { name: string; response: string }[];
  needToken: boolean;
}

const PostMan = () => {
  const [postman, setPostMan] = useState<string>("");
  const [mkdPostman, setMkdPostman] = useState<MkdPostmanItem[]>([]);

  // Transformation function
  function transformCollection(
    collection: PostmanCollection
  ): MkdPostmanItem[] {
    const transformedCollection: MkdPostmanItem[] = [];

    function traverseItems(items: PostmanItem[]) {
      items.forEach((item) => {
        if (item.request) {
          const transformedItem: MkdPostmanItem = {
            method: item.request.method,
            name: item.name,
            url: item.request.url.raw,
            successBody:
              item.response?.find((res) => res.code === 200)?.body || "",
            errors: [],
            needToken: false,
          };

          item.response?.forEach((res) => {
            if (res.code !== 200) {
              const error = {
                name: res.name,
                response: res.body,
              };
              transformedItem.errors.push(error);
            }
          });

          transformedItem.needToken =
            item.request.header?.some(
              (header) =>
                header.key === "Authorization" &&
                header.value.includes("Bearer")
            ) ?? false;

          if (transformedItem.needToken == false) {
            transformedItem.needToken = item.request.auth?.type === "bearer";
          }

          transformedCollection.push(transformedItem);
        }

        if (item.item) {
          traverseItems(item.item);
        }
      });
    }

    traverseItems(collection.item);

    return transformedCollection;
  }

  return (
    <>
      <div className="flex gap-3 justify-center p-2 my-4">
        <div className="p-2 border-2">
          <p>Paste Postman Collection</p>
          <textarea
            className="border-0 border-none"
            cols={58}
            rows={20}
            onChange={(e) => setPostMan(e.target.value)}
          />

          <button
            className="block p-2 my-2 text-gray-200 bg-slate-900"
            onClick={() =>
              setMkdPostman(transformCollection(JSON.parse(postman)))
            }
          >
            Generate
          </button>
        </div>
        <div>
          <textarea
            className="text-green-400 bg-gray-900"
            cols={60}
            rows={20}
            value={formatCode(JSON.stringify(mkdPostman))}
          />
        </div>
      </div>
    </>
  );
};

export default PostMan;
