import type { CommonHeaders } from "@c/validation/sharedSchemas"
import type { FrontendPayloadRequestData } from "types"
import type { FastifyContextConfig, FastifyRequest } from "fastify"

export type RequestWithCommonHeaders<T = unknown> = FastifyRequest<{
  Headers: CommonHeaders
  Params?: T
}>

export const createRequestParams = (
  req: RequestWithCommonHeaders,
  config: FastifyContextConfig,
): FrontendPayloadRequestData => {
  // Get project from req.projectId (set by auth middleware), header, or empty string
  const projectId = (req as any).projectId ?? req.headers["current-project"] ?? ""
  
  const requestParams = {
    appSessionId: req.headers["app-session-id"] ?? "",
    appRequestCode: req.headers["app-request-code"] ?? "",
    requestId: req.id ?? "",
    type: "",
    broadcast: req.headers["app-broadcast-channels"]?.length ? true : false,
    project: projectId,
    userId: req.user?.id,
    options: {},
    ...config,
  }
  // put global query modifiers into requestParams and remove them from params
  if (req?.query?.limit) {
    requestParams.options.limit = req.query.limit
    delete req.query.limit
  }
  if (req?.query?.offset) {
    requestParams.options.offset = req.query.offset
    delete req.query.offset
  }
  if (req?.query?.search) {
    requestParams.options.search = req.query.search
    delete req.query.search
  }
  if (req?.body?.limit) {
    requestParams.options.limit = req.body.limit
    delete req.body.limit
  }
  if (req?.body?.offset) {
    requestParams.options.offset = req.body.offset
    delete req.body.offset
  }
  if (req?.body?.search) {
    requestParams.options.search = req.body.search
    delete req.body.search
  }
  return requestParams
}
