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

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

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

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

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

  return "document";
}

export function createExperienceStoredFilename(mimeType: AllowedMimeType): string {
  return `${randomUUID()}.${ALLOWED_MIME_TO_EXT[mimeType]}`;
}

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

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

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

  return absolute;
}
