import nodeFetch from 'node-fetch';

<% if (postHandler || getHandler) { %>import {<% } %>

<% if (postHandler) { %><%= pascalCaseFileName %>PostInputBody,
  <%= pascalCaseFileName %>PostResultBody,<% } %>
<% if (getHandler) { %><%= pascalCaseFileName %>GetInputQuery,<%= pascalCaseFileName %>GetResultBody,
<% } %>
<% if (postHandler || getHandler) { %>} from './types';<% } %>

export type EndpointConfig = {
  apiUrl: string;
};

<% if (postHandler) { %>
export async function handlePost<%= pascalCaseFileName %>(config: EndpointConfig, requestBody: <%= pascalCaseFileName %>PostInputBody) :Promise<<%= pascalCaseFileName %>PostResultBody> {

  const get<%= pascalCaseFileName %>ServiceUrl = () => `${config.apiUrl}`;

  if (!requestBody) {
    return {
      success: false,
      status: 400,
      error: 'Bad request',
    };
  }

  const url = get<%= pascalCaseFileName %>ServiceUrl();

  try {
    const response = await nodeFetch(url, {
      body: JSON.stringify(requestBody),
      headers: {'Content-Type': 'application/json'},
      method: 'POST',
    });

    if (response.status === 201) {
      const {someValue, id} = await response.json();

      return {
        success: true,
        status: 201,
        data: {id, someResultValue: someValue},
      };
    }

    throw new Error(`Unhandled response with code ${response.status}`);
  } catch (error) {
    // handle error
    return {
      success: false,
      status: 500,
      error: error.message,
    };
  }
}
<% } %>

<% if (getHandler) { %>
  export async function handleGet<%= pascalCaseFileName %>(config: EndpointConfig, {id}: <%= pascalCaseFileName %>GetInputQuery) :Promise<<%= pascalCaseFileName %>GetResultBody> {
     // Define an allow-list of valid IDs or patterns for validation
    const validIdPattern = /^[a-zA-Z0-9_-]+$/;

    const get<%= pascalCaseFileName %>ServiceUrl = (someValue: string) =>
       `${config.apiUrl}/${encodeURIComponent(someValue)}`;

    if (!id || !validIdPattern.test(id)) {
      return {
        status: 400,
        success: false,
        error: 'Bad request',
      };
    }

    const url = get<%= pascalCaseFileName %>ServiceUrl(id);

    try {
      const response = await nodeFetch(url);

      if (response.status === 200) {
        const data = await response.json();

        return {success: true, status: 200, data};
      }

      throw new Error(`Unhandled response with code ${response.status}`);
    } catch (error) {
      //handle error

      return {
        success: false,
        status: 500,
        error: error.message,
      };
    }
  }
<% } %>
