import type { ActionFunctionArgs } from "@remix-run/server-runtime";
import { json } from "@remix-run/server-runtime";
import { ExportLogsServiceRequest, ExportLogsServiceResponse } from "@trigger.dev/otlp-importer";
import { otlpExporter, otlpTransformWorkerPoolEnabled } from "~/v3/otlpExporter.server";

export async function action({ request }: ActionFunctionArgs) {
  try {
    const exporter = await otlpExporter;
    const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";

    if (contentType.startsWith("application/json")) {
      const body = await request.json();

      const exportResponse = await exporter.exportLogs(body as ExportLogsServiceRequest);

      return json(exportResponse, { status: 200 });
    } else if (contentType.startsWith("application/x-protobuf")) {
      const buffer = await request.arrayBuffer();

      if (otlpTransformWorkerPoolEnabled) {
        await exporter.exportLogsRaw(new Uint8Array(buffer));

        return new Response(
          ExportLogsServiceResponse.encode(ExportLogsServiceResponse.create()).finish(),
          { status: 200 }
        );
      }

      const exportRequest = ExportLogsServiceRequest.decode(new Uint8Array(buffer));

      const exportResponse = await exporter.exportLogs(exportRequest);

      return new Response(ExportLogsServiceResponse.encode(exportResponse).finish(), {
        status: 200,
      });
    } else {
      return new Response(
        "Unsupported content type. Must be either application/x-protobuf or application/json",
        { status: 400 }
      );
    }
  } catch (error) {
    console.error(error);

    return new Response("Internal Server Error", { status: 500 });
  }
}
