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

import type { LocalChatMediaRow } from "@/data/storage/chat";

import { localChatMediaRowToBlob } from "../chat_media_blob";

function makeMediaRow(
  overrides: Partial<LocalChatMediaRow> = {},
): LocalChatMediaRow {
  return {
    cacheKey: "user:u1:msg-1:image",
    ownerKey: "user:u1",
    messageId: "msg-1",
    kind: "image",
    remoteUrl: "https://example.com/a.jpg",
    mimeType: "image/jpeg",
    byteSize: 3,
    createdAt: 1,
    updatedAt: 1,
    lastAccessedAt: 1,
    ...overrides,
  };
}

describe("chat media blob helpers", () => {
  it("creates a blob from cached bytes", async () => {
    const blob = localChatMediaRowToBlob(
      makeMediaRow({
        bytes: new Uint8Array([1, 2, 3]).buffer,
      }),
    );

    if (!blob) throw new Error("Expected bytes row to produce a blob.");
    expect(blob.type).toBe("image/jpeg");
    expect(Array.from(new Uint8Array(await blob.arrayBuffer()))).toEqual([
      1, 2, 3,
    ]);
  });

  it("supports legacy blob rows", async () => {
    const blob = localChatMediaRowToBlob(
      makeMediaRow({
        bytes: undefined,
        blob: new Blob([new Uint8Array([4, 5])], { type: "image/png" }),
        mimeType: "",
      }),
    );

    if (!blob) throw new Error("Expected legacy blob row to produce a blob.");
    expect(blob.type).toBe("image/png");
    expect(Array.from(new Uint8Array(await blob.arrayBuffer()))).toEqual([
      4, 5,
    ]);
  });
});
