import { mkdir, stat, writeFile } from "fs/promises";
import path from "path";

import { afterEach, describe, expect, it } from "vitest";

import {
  MEDIA_UPLOAD_ROOT,
  isManagedMediaFilePath,
  removeManagedMediaFile,
  resolveMediaUploadPath,
  sanitizeBaseName,
} from "../lib/media-storage";

const createdFiles: string[] = [];

afterEach(async () => {
  await Promise.all(
    createdFiles.splice(0).map(async (filePath) => {
      await removeManagedMediaFile(filePath);
    }),
  );
});

describe("media storage helpers", () => {
  it("sanitizes upload names safely", () => {
    expect(sanitizeBaseName("Brand Redesign 2026!.svg")).toBe("brand-redesign-2026-svg");
  });

  it("detects managed media upload paths", () => {
    expect(isManagedMediaFilePath("/uploads/media/covers/test.svg")).toBe(true);
    expect(isManagedMediaFilePath("https://example.com/test.svg")).toBe(false);
    expect(isManagedMediaFilePath("../test.svg")).toBe(false);
  });

  it("resolves managed paths inside the upload root", () => {
    const resolvedPath = resolveMediaUploadPath("/uploads/media/assets/test.svg");

    expect(resolvedPath.startsWith(MEDIA_UPLOAD_ROOT)).toBe(true);
    expect(resolvedPath.endsWith(path.join("assets", "test.svg"))).toBe(true);
  });

  it("removes a managed file from disk", async () => {
    const relativePath = `/uploads/media/tests/${Date.now()}-temp.txt`;
    const absolutePath = resolveMediaUploadPath(relativePath);

    await mkdir(path.dirname(absolutePath), { recursive: true });
    await writeFile(absolutePath, "temporary-test-file", "utf8");
    createdFiles.push(relativePath);

    await expect(stat(absolutePath)).resolves.toBeDefined();
    await expect(removeManagedMediaFile(relativePath)).resolves.toBe(true);
    await expect(stat(absolutePath)).rejects.toThrow();
  });
});
