import fs from 'fs';
import crypto from 'crypto';
import { paths } from '../shared/paths.js';

export interface SavedFile {
  type: 'image' | 'document';
  name: string;
  mediaType: string;
  relPath: string;
  absPath: string;
}

export function ensureFileDirs(): void {
  fs.mkdirSync(paths.filesAudio, { recursive: true });
  fs.mkdirSync(paths.filesImages, { recursive: true });
  fs.mkdirSync(paths.filesDocuments, { recursive: true });
}

export function saveAttachment(att: { type: 'image' | 'file'; name: string; mediaType: string; data: string }): SavedFile {
  const category = att.type === 'image' ? 'images' : 'documents';

  const now = new Date();
  const ts = now.toISOString().replace(/[-:T]/g, '').slice(0, 14);
  const stamp = `${ts.slice(0, 8)}_${ts.slice(8, 14)}`;
  const rand = crypto.randomBytes(3).toString('hex');

  // Extract extension from original name or mediaType
  const extFromName = att.name?.includes('.') ? att.name.split('.').pop()! : '';
  const extFromMime: Record<string, string> = {
    'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif', 'image/webp': 'webp',
    'application/pdf': 'pdf', 'text/plain': 'txt', 'text/csv': 'csv',
  };
  const ext = extFromName || extFromMime[att.mediaType] || 'bin';

  const filename = `${stamp}_${rand}.${ext}`;
  const relPath = `${category}/${filename}`;

  const dir = category === 'images' ? paths.filesImages : paths.filesDocuments;
  const absPath = `${dir}/${filename}`;

  fs.writeFileSync(absPath, Buffer.from(att.data, 'base64'));

  return {
    type: att.type === 'image' ? 'image' : 'document',
    name: att.name,
    mediaType: att.mediaType,
    relPath,
    absPath,
  };
}
