import assert from "node:assert/strict";
import { describe, it } from "node:test";
import {
  parseHttpUrl,
  resolveDavUrlFromShareUrl,
  resolveValidatedBlobUrl
} from "./nextcloud-proxy.js";

describe("Nextcloud public share URL handling", () => {
  it("resolves public share URLs to DAV roots", () => {
    assert.equal(
      resolveDavUrlFromShareUrl("https://cloud.example.com/index.php/s/share-token"),
      "https://cloud.example.com/public.php/dav/files/share-token/"
    );
  });

  it("keeps DAV share URLs normalized", () => {
    assert.equal(
      resolveDavUrlFromShareUrl("https://cloud.example.com/public.php/dav/files/share-token/photos"),
      "https://cloud.example.com/public.php/dav/files/share-token/"
    );
  });

  it("rejects non-HTTP URLs and embedded credentials", () => {
    assert.throws(
      () => parseHttpUrl("file:///tmp/photo.jpg", "Invalid image URL."),
      /Invalid image URL/
    );
    assert.throws(
      () => parseHttpUrl("https://user:pass@cloud.example.com/index.php/s/share-token", "Invalid image URL."),
      /URL credentials are not allowed/
    );
  });

  it("allows image URLs inside the selected share", () => {
    assert.equal(
      resolveValidatedBlobUrl(
        "https://cloud.example.com/public.php/dav/files/share-token/folder/photo.jpg",
        "https://cloud.example.com/index.php/s/share-token"
      ),
      "https://cloud.example.com/public.php/dav/files/share-token/folder/photo.jpg"
    );
  });

  it("rejects image URLs outside the selected share", () => {
    assert.throws(
      () => resolveValidatedBlobUrl(
        "https://cloud.example.com/public.php/dav/files/other-token/photo.jpg",
        "https://cloud.example.com/index.php/s/share-token"
      ),
      /outside the requested Nextcloud share/
    );
    assert.throws(
      () => resolveValidatedBlobUrl(
        "https://other.example.com/public.php/dav/files/share-token/photo.jpg",
        "https://cloud.example.com/index.php/s/share-token"
      ),
      /outside the requested Nextcloud share/
    );
  });
});
