import { readFile } from "fs/promises";

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

import { eq } from "drizzle-orm";

import { resolveMediaSelection } from "@/lib/media-service";
import { resolveMediaUploadPath } from "@/lib/media-storage";
import { db } from "@/lib/db";
import { mediaAsset } from "@/lib/db/schema";
import { createMediaAsset } from "@/tests/helpers/factories";
import { canManageUploads } from "@/tests/helpers/fs-capability";

describe("resolveMediaSelection — library mode", () => {
  it("returns the referenced asset", async () => {
    const asset = await createMediaAsset({ url: "https://cdn/lib.png" });
    const result = await resolveMediaSelection({
      media: { mode: "library", assetId: asset.id, url: "", label: "", kind: "IMAGE" },
      uploadFile: null,
      folder: "covers",
      fallbackLabel: "Cover",
      required: false,
    });
    expect(result.assetId).toBe(asset.id);
    expect(result.url).toBe("https://cdn/lib.png");
  });

  it("throws when the referenced asset is missing", async () => {
    await expect(
      resolveMediaSelection({
        media: { mode: "library", assetId: "nope", url: "", label: "", kind: "IMAGE" },
        uploadFile: null,
        folder: "covers",
        fallbackLabel: "Cover",
        required: true,
      }),
    ).rejects.toThrow(/not found/i);
  });
});

describe("resolveMediaSelection — external mode", () => {
  it("creates a new external asset from the url", async () => {
    const result = await resolveMediaSelection({
      media: { mode: "external", assetId: "", url: "https://cdn/new/photo.png", label: "Photo", kind: "IMAGE" },
      uploadFile: null,
      folder: "covers",
      fallbackLabel: "Cover",
      required: true,
    });
    expect(result.createdAssetId).toBeTruthy();
    expect(result.url).toBe("https://cdn/new/photo.png");

    const stored = await db.query.mediaAsset.findFirst({ where: eq(mediaAsset.id, result.assetId!) });
    expect(stored?.source).toBe("EXTERNAL");
    expect(stored?.fileName).toBe("photo.png");
    expect(stored?.label).toBe("Photo");
  });

  it("returns empty selection for a not-required empty url", async () => {
    const result = await resolveMediaSelection({
      media: { mode: "external", assetId: "", url: "", label: "", kind: "IMAGE" },
      uploadFile: null,
      folder: "covers",
      fallbackLabel: "Cover",
      required: false,
    });
    expect(result.assetId).toBeNull();
    expect(result.url).toBe("");
  });
});

describe("resolveMediaSelection — missing configuration", () => {
  it("throws when required and no media object is present", async () => {
    await expect(
      resolveMediaSelection({ media: undefined, uploadFile: null, folder: "covers", fallbackLabel: "L", required: true }),
    ).rejects.toThrow(/missing/i);
  });

  it("returns empty selection when not required and no media object is present", async () => {
    const result = await resolveMediaSelection({
      media: undefined,
      uploadFile: null,
      folder: "covers",
      fallbackLabel: "L",
      required: false,
    });
    expect(result.assetId).toBeNull();
  });

  it("throws for a required upload with no file", async () => {
    await expect(
      resolveMediaSelection({
        media: { mode: "upload", assetId: "", url: "", label: "", kind: "IMAGE" },
        uploadFile: null,
        folder: "covers",
        fallbackLabel: "L",
        required: true,
      }),
    ).rejects.toThrow(/required/i);
  });
});

describe("resolveMediaSelection — upload mode (filesystem)", () => {
  it.skipIf(!canManageUploads)("saves the file and creates an UPLOAD asset", async () => {
    const file = new File([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], "shot.png", { type: "image/png" });
    const result = await resolveMediaSelection({
      media: { mode: "upload", assetId: "", url: "", label: "Shot", kind: "IMAGE" },
      uploadFile: file,
      folder: "tests",
      fallbackLabel: "L",
      required: true,
    });
    expect(result.uploadedUrl).toBeTruthy();
    const stored = await db.query.mediaAsset.findFirst({ where: eq(mediaAsset.id, result.assetId!) });
    expect(stored?.source).toBe("UPLOAD");
    // File actually written to disk
    const bytes = await readFile(resolveMediaUploadPath(result.url));
    expect(bytes.length).toBeGreaterThan(0);
    // cleanup
    const { removeManagedMediaFile } = await import("@/lib/media-storage");
    await removeManagedMediaFile(result.url);
  });
});
