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

const DEFAULT_UPLOAD_DIR = "/home/mdares03/benell/uploads/projects";

export const PROJECT_UPLOAD_DIR = process.env.PROJECT_UPLOAD_DIR?.trim() || DEFAULT_UPLOAD_DIR;
export const 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 isAllowedMimeType(mimeType: string): mimeType is AllowedMimeType {
  return Object.prototype.hasOwnProperty.call(ALLOWED_MIME_TO_EXT, mimeType);
}

export function getEvidenceKindFromMimeType(mimeType: string): ProjectCaptureEvidenceKind {
  if (mimeType.startsWith("image/")) {
    return "photo";
  }

  if (mimeType === "application/pdf") {
    return "document";
  }

  return "document";
}

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

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

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

  const absolute = path.resolve(PROJECT_UPLOAD_DIR, normalized);
  const root = path.resolve(PROJECT_UPLOAD_DIR);

  if (!(absolute === root || absolute.startsWith(`${root}${path.sep}`))) {
    return null;
  }

  return absolute;
}
