import { readOperationTypesList } from "@racletteCore/constants/ApiClient"
import { CUD_HTTP_METHODS, CUD_OPERATION_TYPES } from "../constants"
import type { CoreCudOperationType, CoreReadOperationType } from "@racletteCore"
import type { RouteConfig, Operations } from "../types"
import { replaceUrlParams } from "@racletteCore/lib/uriParser"

// Helper functions for better readability
export const isCudHttpMethod = (method: string): boolean =>
  CUD_HTTP_METHODS.includes(method as any)

export const isCudOperationType = (
  storeActionType: string,
): storeActionType is CoreCudOperationType =>
  CUD_OPERATION_TYPES.has(storeActionType as CoreCudOperationType)

export const isCudOperation = (routeConfig: RouteConfig): boolean => {
  // If there's a storeActionType, check it first
  if (routeConfig.storeActionType) {
    // If it's explicitly a read operation type, it's not CUD
    if (
      readOperationTypesList.includes(
        routeConfig.storeActionType as CoreReadOperationType,
      )
    ) {
      return false
    }
    // If it's explicitly a CUD operation type, it is CUD
    if (isCudOperationType(routeConfig.storeActionType)) {
      return true
    }
    // If storeActionType is neither read nor CUD type, fall back to HTTP method
  }

  // Default to HTTP method-based classification
  return isCudHttpMethod(routeConfig.method)
}

export const splitOperations = <T extends Operations>(
  operations: T,
): {
  cudOperations: Partial<T>
  readOperations: Partial<T>
} => {
  const entries = Object.entries(operations)

  const cudEntries = entries.filter(([, routeConfig]) =>
    isCudOperation(routeConfig),
  )
  const readEntries = entries.filter(
    ([, routeConfig]) => !isCudOperation(routeConfig),
  )

  return {
    cudOperations: Object.fromEntries(cudEntries) as Partial<T>,
    readOperations: Object.fromEntries(readEntries) as Partial<T>,
  }
}

export const createPluginActionId = (
  dataType: string,
  actionId: string,
): string => `${dataType}-${actionId}`

export const validatePluginMetadata = (metadata: any): boolean => {
  return (
    metadata &&
    typeof metadata.name === "string" &&
    typeof metadata.author === "string"
  )
}
export const handleOperationTarget = (
  target: String | Function,
  params: Object,
): String => {
  let _target = target || ""
  if (typeof _target === "function") _target = target(params)
  if (_target && _target.includes(":"))
    _target = replaceUrlParams(_target, params)
  return _target
}
export const prefixOperationTarget = (
  target: String,
  prefix: String,
): String => {
  let validTarget = target || ""
  if (target && target.indexOf("/") === 0) {
    validTarget = `${prefix}${target}`
  } else {
    validTarget = `${prefix}/${target}`
  }
  return validTarget
}
