import { randomUUID } from "crypto";
import { mkdir } from "fs/promises";
import path from "path";
import type { CaptureEvidenceKindDTO } from "@/lib/capture/types";

const DEFAULT_CAPTURE_UPLOAD_DIR = "/home/mdares03/benell/uploads/capture";

export const CAPTURE_UPLOAD_DIR = process.env.CAPTURE_UPLOAD_DIR?.trim() || DEFAULT_CAPTURE_UPLOAD_DIR;
export const CAPTURE_MAX_UPLOAD_BYTES = 10 * 1024 * 1024;

const ALLOWED_MIME_TO_EXT = {
  "image/jpeg": "jpg",
  "image/png": "png",
  "image/webp": "webp",
  "application/pdf": "pdf",
} as const;

type AllowedMimeType = keyof typeof ALLOWED_MIME_TO_EXT;

export function isAllowedCaptureMimeType(mimeType: string): mimeType is AllowedMimeType {
  return Object.prototype.hasOwnProperty.call(ALLOWED_MIME_TO_EXT, mimeType);
}

export function createCaptureStoredFilename(mimeType: AllowedMimeType): string {
  const extension = ALLOWED_MIME_TO_EXT[mimeType];
  return `${randomUUID()}.${extension}`;
}

export function getCaptureEvidenceKindFromMimeType(mimeType: string): Exclude<CaptureEvidenceKindDTO, "link"> {
  if (mimeType.startsWith("image/")) {
    return "photo";
  }

  return "document";
}

export async function ensureCaptureUploadDir(): Promise<void> {
  await mkdir(CAPTURE_UPLOAD_DIR, { recursive: true });
}

export function resolveCaptureStoragePath(storagePath: string): string | null {
  const normalized = storagePath.trim();
  if (!normalized) {
    return null;
  }

  const absolute = path.resolve(CAPTURE_UPLOAD_DIR, normalized);
  const root = path.resolve(CAPTURE_UPLOAD_DIR);
  if (!(absolute === root || absolute.startsWith(`${root}${path.sep}`))) {
    return null;
  }

  return absolute;
}
