import fs from "fs/promises";
import path from "path";
import crypto from "crypto";

const UPLOADS_ROOT = process.env.UPLOADS_DIR || path.join(process.cwd(), "uploads");

function sanitizeFilename(name: string): string {
  return name.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 150);
}

export async function saveAttachment(
  contactId: number,
  messageId: number,
  originalFilename: string,
  buffer: Buffer
): Promise<{ relativePath: string; absolutePath: string }> {
  const dir = path.join(UPLOADS_ROOT, String(contactId));
  await fs.mkdir(dir, { recursive: true });

  const unique = crypto.randomBytes(6).toString("hex");
  const safeName = sanitizeFilename(originalFilename);
  const filename = `${messageId}-${unique}-${safeName}`;

  const absolutePath = path.join(dir, filename);
  await fs.writeFile(absolutePath, buffer);

  const relativePath = path.join(String(contactId), filename);
  return { relativePath, absolutePath };
}

export function attachmentAbsolutePath(relativePath: string): string {
  return path.join(UPLOADS_ROOT, relativePath);
}
