import * as fs from 'fs';
import * as path from 'path';

function uploadsDirectory() {
  return path.join(__dirname, '../public/uploads');
}

export function resolveUploadFilePath(imageUrl: string): string | null {
  if (!imageUrl) return null;

  const normalized = String(imageUrl).trim().replace(/^\/public/, '');
  if (!normalized.startsWith('/uploads/')) return null;

  const filename = path.basename(normalized);
  if (!filename || filename.includes('..')) return null;

  return path.join(uploadsDirectory(), filename);
}

export function deleteUploadFile(imageUrl: string | null | undefined) {
  const filePath = resolveUploadFilePath(String(imageUrl || ''));
  if (!filePath || !fs.existsSync(filePath)) return;

  try {
    fs.unlinkSync(filePath);
  } catch {
    // Ignore missing or locked files.
  }
}

export function copyFileToUploads(sourceAbsolutePath: string, preferredBaseName: string) {
  if (!fs.existsSync(sourceAbsolutePath)) {
    throw new Error(`Source file not found: ${sourceAbsolutePath}`);
  }

  const uploadsDir = uploadsDirectory();
  fs.mkdirSync(uploadsDir, { recursive: true });

  const ext = path.extname(sourceAbsolutePath) || '.jpeg';
  const slug = preferredBaseName
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '');

  let filename = `${slug}${ext}`;
  let counter = 1;
  while (fs.existsSync(path.join(uploadsDir, filename))) {
    filename = `${slug}-${counter}${ext}`;
    counter += 1;
  }

  fs.copyFileSync(sourceAbsolutePath, path.join(uploadsDir, filename));
  return `/uploads/${filename}`;
}
