export const makeBaasPostmanSchema = (endpoints) => {
  let postman = [];

  endpoints.forEach((endpoint, index) => {
    postman.push({
      method: endpoint.method,
      name: endpoint.name,
      url: `{baseUrl}${endpoint.route}`,
      successBody: endpoint.response,
      errors: []
    })
  })

  return postman;
}

export const makeBaasPostmanSchemaTemplate = (endpoints) => {
  let postman = "[";

  endpoints.forEach((endpoint, index) => {

    postman += `{
            'method': "${endpoint.method}",
            'name': "${endpoint.name}",
            'url': "{baseUrl}${endpoint.route}",
            'successBody': \"${endpoint.response}"\,
            'needToken': "${endpoint.protected}",
            'errors': []
        },
        `;
  })

  postman += "]";

  return `${postman}`;
}

function generateRawBody(inputs) {
  const body = {};

  inputs.forEach(input => {
    if (input.type === 'body') {
      // Initialize the value based on the dataType
      let value;
      switch (input.dataType.toLowerCase()) {
        case 'integer':
        case 'integer?':
          value = 0; // Default integer value
          break;
        case 'string':
        case 'string?':
          value = ""; // Default string value
          break;
        default:
          value = null; // Default for other types
      }
      body[input.name] = value;
    }
  });

  return JSON.stringify(body, null, 2); // Convert to JSON string with indentation
}

export const buildRequest = (obj, project = {}) => {
  console.log("obj:",obj)
  const request = {
    name: obj.name,
    request: {
      method: obj.method,
      header: [],
      url: {
        raw: '{{baseurl}}' + `${obj.route}`,
        host: ["{{baseurl}}"],
        path: [`${obj.route}`]
      },
      body: {},
      description: ''
    },
    response: []
  };

  request.request.header.push({
    key: 'x-project',
    value: btoa(`${project.slug}:${project.secret}`),
    type: 'text'
  });

  if (obj.protected) {
    request.request.header.push({
      key: 'Authorization',
      value: 'Bearer <your_token_here>',
      type: 'text'
    });
  }

  for (const input of obj.inputs) {
    if (input.type === 'query') {
      request.request.url.query = request.request.url.query || [];
      request.request.url.query.push({
        key: input.name,
        value: '',
        type: input.dataType,
        description: ''
      });
    } else if (input.type === 'body') {
      request.request.body.mode = 'raw';
      request.request.body.raw = generateRawBody(obj.inputs); // Use the new function
      request.request.body.options = {
        raw: {
          language: 'json'
        }
      };
    } else if (input.type === 'path' || input.type === 'multipart') {
      request.request.url.variable = request.request.url.variable || [];
      request.request.url.variable.push({
        key: input.name,
        value: '',
        description: ''
      });
    }
  }

  return request;
}


export const makePostmanCollection = (endpoints, project = {}) => {
  let requests = [];
  const customRequests = {
    name: "custom",
    item: [],
  };

  const lamgdaList = [];
  const lamdaKeys = [];
  const treeqlKeys = [];
  const treeqlList = [];

  const findSplits = (str) => str.split(" ")[1];

  for (const obj of endpoints) {
    const newRequest = buildRequest(obj, project);

    if (obj.group === "custom") {
      customRequests.item.push(newRequest);
    } else if (obj.group === "treeql") {
      if (!treeqlKeys.includes(findSplits(obj.name))) {
        treeqlKeys.push(findSplits(obj.name));
        treeqlList.push({
          name: findSplits(obj.name),
          item: [],
        });
      }

      for (const item of treeqlList) {
        if (item.name === findSplits(obj.name)) {
          item.item.push(newRequest);
        }
      }
    } else {
      if (!lamdaKeys.includes(obj.group)) {
        lamdaKeys.push(obj.group);
        lamgdaList.push({
          name: obj.group,
          item: [],
        });
      }
      for (const item of lamgdaList) {
        if (item.name === obj.group) {
          item.item.push(newRequest);
        }
      }
    }
  }

  console.log(treeqlKeys)

  const lamdaRequests = {
    name: "lamda",
    item: [...lamgdaList],
  };

  const treeqlRequests = {
    name: "treeql",
    item: [...treeqlList],
  };

  requests = [customRequests, lamdaRequests, treeqlRequests];

  const collection = {
    info: {
      name: ` ${project.slug} Collection`,
      description: `${project.slug} collection BAAS`,
      schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json',
      _postman_variable_scope: 'environment',
      _postman_exported_at: new Date().toISOString(),
      _postman_exported_using: 'BAAS'
    },
    item: requests,
    variable: [
      {
        key: 'baseurl',
        value: `https://${project.slug}.mkdlabs.com`,
        type: 'string'
      }
    ]
  };

  return JSON.stringify(collection, null, 2);
}