import "server-only";

import { extractVideoMetadata } from "@/lib/media-processing";
import { createErrorResponse, createSuccessResponse } from "@/lib/server";
import { cleanupFiles, writeUploadToTemp } from "@/lib/uploads";
import { validateVideoUploadFile } from "@/lib/validations";

export async function handleVideoMetadataRequest(
  request: Request,
  fallbackErrorMessage = "Failed to load video metadata."
) {
  let uploadPath: string | null = null;

  try {
    const formData = await request.formData();
    const fileEntry = formData.get("file");

    if (!(fileEntry instanceof File)) {
      throw new Error("Missing video file.");
    }

    validateVideoUploadFile(fileEntry);
    const uploadedFile = await writeUploadToTemp(fileEntry);
    uploadPath = uploadedFile.tempPath;

    const metadata = await extractVideoMetadata(uploadedFile.tempPath, uploadedFile.originalName);
    return createSuccessResponse(metadata);
  } catch (error) {
    return createErrorResponse(error, fallbackErrorMessage);
  } finally {
    await cleanupFiles([uploadPath]);
  }
}
