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

import { mediaFieldInputSchema } from "@/lib/media-validation";

const base = { assetId: "", url: "", label: "", kind: "IMAGE" as const };

describe("mediaFieldInputSchema", () => {
  it("accepts a valid library selection", () => {
    const parsed = mediaFieldInputSchema.parse({ ...base, mode: "library", assetId: "asset_1" });
    expect(parsed.mode).toBe("library");
    expect(parsed.assetId).toBe("asset_1");
  });

  it("requires an assetId in library mode", () => {
    expect(() => mediaFieldInputSchema.parse({ ...base, mode: "library" })).toThrow(/media asset/i);
  });

  it("accepts a valid external url", () => {
    const parsed = mediaFieldInputSchema.parse({ ...base, mode: "external", url: "https://cdn/x.png" });
    expect(parsed.url).toBe("https://cdn/x.png");
  });

  it("accepts a root-relative external url", () => {
    const parsed = mediaFieldInputSchema.parse({ ...base, mode: "external", url: "/uploads/media/x.png" });
    expect(parsed.url).toBe("/uploads/media/x.png");
  });

  it("requires a url in external mode", () => {
    expect(() => mediaFieldInputSchema.parse({ ...base, mode: "external" })).toThrow(/URL/i);
  });

  it("rejects malformed urls", () => {
    expect(() =>
      mediaFieldInputSchema.parse({ ...base, mode: "external", url: "not-a-url" }),
    ).toThrow(/absolute URL or start with/i);
  });

  it("accepts upload mode without asset or url", () => {
    const parsed = mediaFieldInputSchema.parse({ ...base, mode: "upload" });
    expect(parsed.mode).toBe("upload");
  });

  it("rejects an unknown mode", () => {
    expect(() => mediaFieldInputSchema.parse({ ...base, mode: "sideload" })).toThrow();
  });

  it("rejects an invalid media kind", () => {
    expect(() =>
      mediaFieldInputSchema.parse({ ...base, mode: "upload", kind: "VIDEO" }),
    ).toThrow();
  });

  it("trims text fields and defaults optionals to empty strings", () => {
    const parsed = mediaFieldInputSchema.parse({
      mode: "library",
      assetId: "  asset_9  ",
      label: "  Logo  ",
      kind: "IMAGE",
    });
    expect(parsed.assetId).toBe("asset_9");
    expect(parsed.label).toBe("Logo");
    expect(parsed.url).toBe("");
  });
});
