import fs from "fs";
import path from "path";
import { v4 as uuid } from "uuid";

const STORAGE_ROOT = path.join(process.cwd(), "storage");
const PERMANENT_DIR = path.join(STORAGE_ROOT, "permanent");
const TEMP_DIR = path.join(STORAGE_ROOT, "temp");
const LIBRARY_FILE = path.join(STORAGE_ROOT, "library.json");

function ensureStorageLayout() {
  if (!fs.existsSync(STORAGE_ROOT)) {
    fs.mkdirSync(STORAGE_ROOT, { recursive: true });
  }

  if (!fs.existsSync(PERMANENT_DIR)) {
    fs.mkdirSync(PERMANENT_DIR, { recursive: true });
  }

  if (!fs.existsSync(TEMP_DIR)) {
    fs.mkdirSync(TEMP_DIR, { recursive: true });
  }

  if (!fs.existsSync(LIBRARY_FILE)) {
    fs.writeFileSync(LIBRARY_FILE, JSON.stringify([]));
  }
}

function readLibrary() {
  try {
    const raw = fs.readFileSync(LIBRARY_FILE, { encoding: "utf8" });
    return JSON.parse(raw);
  } catch (error) {
    console.error("Failed to read library file", error);
    return [];
  }
}

function writeLibrary(entries) {
  fs.writeFileSync(LIBRARY_FILE, JSON.stringify(entries, null, 2));
}

function registerUploadedFile(file, { permanent, uploader = "unknown" }) {
  ensureStorageLayout();
  const createdAt = new Date().toISOString();
  let finalPath = file.path;
  let storedName = path.basename(file.path);
  let permanentEntry = null;

  if (permanent) {
    const extension = path.extname(file.originalname) || "";
    storedName = `${uuid()}${extension}`;
    finalPath = path.join(PERMANENT_DIR, storedName);
    fs.renameSync(file.path, finalPath);
    permanentEntry = {
      id: uuid(),
      originalName: file.originalname,
      storedName,
      path: finalPath,
      size: file.size,
      mimetype: file.mimetype,
      uploader,
      createdAt,
    };
    const library = readLibrary();
    library.push(permanentEntry);
    writeLibrary(library);
  }

  return {
    id: uuid(),
    title: file.originalname,
    originalName: file.originalname,
    path: finalPath,
    storedName,
    size: file.size,
    mimetype: file.mimetype,
    permanent,
    uploader,
    libraryTrackId: permanentEntry ? permanentEntry.id : null,
    createdAt,
  };
}

function getPermanentLibrary() {
  ensureStorageLayout();
  return readLibrary();
}

function findPermanentTrack(id) {
  return getPermanentLibrary().find((entry) => entry.id === id);
}

function createQueueTrackFromLibrary(libraryTrack, requestedBy = "library") {
  if (!libraryTrack) {
    return null;
  }

  return {
    id: uuid(),
    title: libraryTrack.originalName,
    originalName: libraryTrack.originalName,
    path: libraryTrack.path,
    storedName: libraryTrack.storedName,
    size: libraryTrack.size,
    mimetype: libraryTrack.mimetype,
    permanent: true,
    uploader: requestedBy,
    libraryTrackId: libraryTrack.id,
    createdAt: new Date().toISOString(),
  };
}

function deleteFileSafe(filePath) {
  if (!filePath) {
    return;
  }

  try {
    fs.existsSync(filePath) && fs.unlinkSync(filePath);
  } catch (error) {
    console.error(`Failed to delete file ${filePath}`, error);
  }
}

function deletePermanentTrack(id) {
  const library = getPermanentLibrary();
  const index = library.findIndex((entry) => entry.id === id);
  if (index === -1) {
    return null;
  }

  const [removed] = library.splice(index, 1);
  writeLibrary(library);
  deleteFileSafe(removed.path);
  return removed;
}

function handleTrackCompletion(track) {
  if (!track || track.permanent) {
    return;
  }
  deleteFileSafe(track.path);
}

function deleteTrackFile(track) {
  if (!track) {
    return;
  }

  if (!track.permanent) {
    deleteFileSafe(track.path);
  }
}

export {
  PERMANENT_DIR,
  TEMP_DIR,
  ensureStorageLayout,
  registerUploadedFile,
  getPermanentLibrary,
  findPermanentTrack,
  createQueueTrackFromLibrary,
  deletePermanentTrack,
  handleTrackCompletion,
  deleteTrackFile,
};
