import { app } from 'electron';
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';

const FILENAME_MAX = 200;

function sanitizeFilename(name: string): string {
  const stripped = name
    .replace(/[\\/]/g, '_')
    // eslint-disable-next-line no-control-regex
    .replace(/[\x00-\x1f]/g, '')
    .replace(/^\.+/, '');
  return stripped.length > FILENAME_MAX ? stripped.slice(0, FILENAME_MAX) : stripped;
}

export function attachmentsRoot(): string {
  return path.join(app.getPath('userData'), 'attachments');
}

export function absolutePath(storedPath: string): string {
  return path.join(attachmentsRoot(), storedPath);
}

export async function copyIntoTask(
  taskId: string,
  sourcePath: string,
  filename: string,
): Promise<{ storedPath: string }> {
  const safeName = sanitizeFilename(filename);
  const dir = path.join(attachmentsRoot(), taskId);
  await fs.mkdir(dir, { recursive: true });
  const finalName = `${randomUUID()}-${safeName}`;
  const dest = path.join(dir, finalName);
  await fs.copyFile(sourcePath, dest);
  return { storedPath: path.join(taskId, finalName) };
}

export async function deleteStored(storedPath: string): Promise<void> {
  const abs = absolutePath(storedPath);
  await fs.unlink(abs).catch((err) => {
    if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
  });
}

export async function deleteTaskDir(taskId: string): Promise<void> {
  const dir = path.join(attachmentsRoot(), taskId);
  await fs.rm(dir, { recursive: true, force: true });
}
