import {
  DeployManager,
  InvalidRequest2,
  NotFoundError,
  S3Client2
} from "../chunk-FO7L563E.js";
import "../chunk-IUKLHJNE.js";
import "../chunk-FRWSD3YQ.js";
import "../chunk-QAE2S7MG.js";
import "../chunk-X6XO7USX.js";
import "../chunk-UT2RMOJS.js";
import "../chunk-TJ744C2T.js";
import "../chunk-64IS37V6.js";
import "../chunk-XLUI7RQ4.js";
import "../chunk-JBVMOFGH.js";
import "../chunk-JSBRDJBE.js";

// src/lambda/utils/parseAppName.ts
function parseAppName(uri) {
  const [, , appName] = uri.split("/");
  return appName;
}

// src/lambda/utils/parseGroupId.ts
function parseGroupId(uri) {
  const [, , , groupId] = uri.split("/");
  return groupId;
}

// src/lambda/utils/parsePlatform.ts
function parsePlatform(uri) {
  if (uri.startsWith("/ios")) {
    return "ios";
  }
  if (uri.startsWith("/android")) {
    return "android";
  }
  throw new InvalidRequest2(`URI must start with /ios or /android. uri: ${uri}`);
}

// src/lambda/utils/parseSuffix.ts
function parseSuffix(uri) {
  const [, , , , tag] = uri.split("/");
  if (tag == null || tag?.length === 0) {
    throw new InvalidRequest2(`unable to parse suffix: ${uri}`);
  }
  return tag;
}

// src/lambda/origin-request.ts
function createOriginRequestHandler(context) {
  const s3Client = new S3Client2({
    bucket: context.bucketName,
    region: context.region
  });
  return async function handler2(event) {
    try {
      const request = event.Records[0]?.cf?.request;
      if (request == null) {
        throw new InvalidRequest2("request is null");
      }
      const appName = parseAppName(request.uri);
      const platform = parsePlatform(request.uri);
      const groupId = parseGroupId(request.uri);
      const suffix = parseSuffix(request.uri);
      if (appName == null || platform == null || groupId == null) {
        throw new InvalidRequest2("invalid request");
      }
      const deploymentId = await DeployManager.resolveDeploymentId(
        {
          appName,
          groupId,
          allowAccessCluster: context.allowAccessCluster
        },
        {
          s3Client
        }
      );
      const bundlePath = DeployManager.resolveBundle({
        appName,
        platform,
        deploymentId,
        tag: suffix !== "bundle" ? suffix : void 0
      });
      const absolutePath = `/${bundlePath}`;
      request.uri = absolutePath;
      request.headers["x-bundle"] = [
        {
          key: "X-Bundle",
          value: absolutePath
        }
      ];
      return request;
    } catch (error) {
      if (error instanceof NotFoundError) {
        return { status: "404", statusDescription: error.message };
      }
      if (error instanceof InvalidRequest2) {
        return { status: "400", statusDescription: error.message };
      }
      throw error;
    }
  };
}
var handler = createOriginRequestHandler({
  allowAccessCluster: false,
  bucketName: _BUCKET_NAME,
  region: _BUCKET_REGION
});
export {
  createOriginRequestHandler,
  handler
};
