import { StringCaser } from "@/utils/utils";
import { getType } from "../utils/helpers";

export default (configuration) => {
  //TODO: add functions for api
  return `
package ${configuration.packageName}.network

import ${configuration.packageName}.model.remote.*
import okhttp3.MultipartBody
import retrofit2.Response
import retrofit2.http.*

interface ApiService {

  //Build Interface based on all Api endpoints

  @POST("/v1/api/rest/user/GETALL")
    suspend fun getAllUser(): Response<FriendListResponse>

  @POST("/v3/api/lambda/realtime/room")
    suspend fun createRoomRequests(@Body request: CreateRoomRequests): Response<CreateRoomResponse>


  @POST("/v3/api/lambda/realtime/chat")
    suspend fun getChats(@Body request: ChatRequest): Response<ChatResponse>

    @GET("/v3/api/lambda/realtime/room/poll")
    suspend fun getStartPool(@Query("user_id") customDate: Int?): Response<SingleChatMessageResponse>


    @GET("/v4/api/records/room")
    suspend fun getAllRoom(@Query("user_id") id: Int?): Response<ChatRoomResponse>

    
    @POST("/v5/api/deployments/wireframe/ask-gpt-custom")
    suspend fun sendMessageToBot(@Body json: String): Response<ChatBotTextResponse>


    @POST("/v5/api/deployments/wireframe/ask-gpt-custom")
    suspend fun sendMessageToBot(@Body request: ChatBotRequest): Response<ChatBotTextResponse>


    @POST("/v3/api/lambda/realtime/send")
    suspend fun sendTextMessage(@Body request: ChatTextRequest): Response<ChatTextResponse>
 

  ${buildApi(configuration.api)}

}
  `;
};

const buildApi = (apis) => {
  let endpoints = [];
  apis?.map((api) => {
    //@GET("v4/api/records/app_uses")
    endpoints.push(`
      ${getMultipartAnnotation(api)}
      ${buildRouteAnnotation(api)}
      ${buildAbstractFunction(api)}
    `);
  });
  return endpoints.join("\n");
};

const getMultipartAnnotation = (api) => {
  // @Multipart
  if (api?.inputs.filter((input) => input.type == "multipart").length > 0) {
    return `@Multipart`;
  }
  return ``;
};
const buildRouteAnnotation = (api) => {
  //@GET("v4/api/records/app_uses")
  return `@${StringCaser(api?.method, {
    casetype: "uppercase",
  })}("${replaceEndpointFormat(api.route)}")`;
};

const buildAbstractFunction = (api) => {
  //suspend fun getAllUses(): Response<AllUsesResponse>
  return `suspend fun ${StringCaser(api?.name, {
    casetype: "camelCase",
  })}(${buildFunctionArgs(api)}): Response<${StringCaser(api.name, {
    casetype: "PascalCase",
  })}Response>`;
};

const buildFunctionArgs = (api) => {
  const body = buildBody(
    api?.inputs.filter((input) => input.type == "body"),
    api
  );
  const paths = buildPaths(
    api?.inputs.filter((input) => input.type == "path"),
    api
  );
  const query = buildQueries(
    api?.inputs.filter((input) => input.type == "query"),
    api
  );
  const multipart = buildMultipart(
    api?.inputs.filter((input) => input.type == "multipart"),
    api
  );
  return `${body} ${paths} ${query} ${multipart}`;
};

const buildMultipart = (inputs, api) => {
  if (inputs.length == 0) return "";
  //@Part file: MultipartBody.Part
  return ` ${inputs
    .map((input) => `@Part ${input.name}: MultipartBody.Part`)
    .map((query) => `       ${query}`)
    .join(",\n")} `;
};

const buildPaths = (inputs, api) => {
  if (inputs.length == 0) return "";
  //@Path("id") id: Int
  return ` ${inputs
    .map(
      (input) =>
        `@Path("${input.name}") ${StringCaser(input.name, {
          casetype: "camelCase",
        })}: ${getType(input.dataType)}`
    )
    .map(
      (query, index) =>
        `       ${query}${index === inputs.length - 1 ? "," : ""}`
    )
    .join(",\n")} `;
};

const buildQueries = (inputs, api) => {
  if (inputs.length == 0) return "";
  //@Query("chat_id") chatId: Int

  return ` ${inputs
    .map(
      (input) =>
        `@Query("${input.name}") ${StringCaser(input.name, {
          casetype: "camelCase",
        })}: ${getType(input.dataType)}`
    )
    .map(
      (query, index) =>
        `       ${query}${index === inputs.length - 1 ? "," : ""}`
    )
    .join(",\n")} `;
};

const buildBody = (inputs, api) => {
  if (inputs.length == 0) return "";
  //@Body request: TranslateRequest
  const requestName = StringCaser(api.name, { casetype: "PascalCase" });
  return `@Body request: ${requestName}Request,`;
};

function replaceEndpointFormat(endpoint) {
  return endpoint.replace(/:[^/]+/g, (match) => `{${match.substring(1)}}`);
}
