import { describe, it, expect, vi, beforeEach } from "vitest";
import { resizeOrgIcon, buildOrgIconKey, ICON_SIZES, ORG_ICONS_BUCKET } from "./orgIcons.js";

describe("buildOrgIconKey", () => {
  it("builds the correct R2 key for a given org and size", () => {
    expect(buildOrgIconKey(42, 192)).toBe("org-icons/42/icon-192.png");
  });

  it("builds the correct key for maskable variant", () => {
    expect(buildOrgIconKey(42, 512, true)).toBe("org-icons/42/icon-512-maskable.png");
  });
});

describe("ICON_SIZES", () => {
  it("includes all required PWA icon sizes", () => {
    const sizes = ICON_SIZES.map((s) => s.size);
    expect(sizes).toContain(16);
    expect(sizes).toContain(32);
    expect(sizes).toContain(180);
    expect(sizes).toContain(192);
    expect(sizes).toContain(512);
  });

  it("includes a maskable 512 variant", () => {
    const maskable = ICON_SIZES.find((s) => s.maskable);
    expect(maskable).toBeDefined();
    expect(maskable!.size).toBe(512);
  });
});

describe("resizeOrgIcon", () => {
  it("returns buffers for all required sizes from a valid PNG input", async () => {
    const sharp = (await import("sharp")).default;
    const input = await sharp({
      create: { width: 512, height: 512, channels: 4, background: { r: 255, g: 0, b: 0, alpha: 1 } },
    })
      .png()
      .toBuffer();

    const results = await resizeOrgIcon(input);

    expect(results).toHaveLength(ICON_SIZES.length);
    for (const result of results) {
      expect(result.buffer).toBeInstanceOf(Buffer);
      expect(result.buffer.length).toBeGreaterThan(0);
    }
  });

  it("rejects images smaller than 512x512", async () => {
    const sharp = (await import("sharp")).default;
    const tooSmall = await sharp({
      create: { width: 256, height: 256, channels: 4, background: { r: 0, g: 0, b: 255, alpha: 1 } },
    })
      .png()
      .toBuffer();

    await expect(resizeOrgIcon(tooSmall)).rejects.toThrow("minimum 512x512");
  });
});
