import { describe, expect, it } from "vitest";
import { resolveTeamAvatarData, resolveUserAvatarData } from "~/lib/avatar-data";
import { generateFlagConfig } from "~/lib/flag-generator";
import { FLAG_PATTERNS, isFlagConfig } from "~/lib/flag-types";

describe("generateFlagConfig", () => {
  it("generates the same flag for the same seed", () => {
    expect(generateFlagConfig("user-1")).toEqual(generateFlagConfig("user-1"));
  });

  it("generates valid configs", () => {
    const config = generateFlagConfig("team-9");
    expect(FLAG_PATTERNS).toContain(config.pattern);
    expect(config.colors).toHaveLength(3);
    expect(isFlagConfig(config)).toBe(true);
  });
});

describe("avatar data resolution", () => {
  it("returns uploaded avatar when avatarType is uploaded", () => {
    expect(resolveUserAvatarData({
      id: "user-1",
      avatarType: "uploaded",
      customAvatarUrl: "https://example.com/avatar.jpg",
      flagConfig: generateFlagConfig("user-1"),
    })).toEqual({ type: "image", url: "https://example.com/avatar.jpg" });
  });

  it("returns flag when avatarType is uploaded but no customAvatarUrl", () => {
    const avatar = resolveUserAvatarData({ id: "user-1", avatarType: "uploaded" });
    expect(avatar.type).toBe("flag");
  });

  it("returns flag regardless of oauth imageUrl being present", () => {
    const avatar = resolveUserAvatarData({ id: "user-2", avatarType: "flag" });
    expect(avatar.type).toBe("flag");
    if (avatar.type === "flag") {
      expect(avatar.config).toEqual(generateFlagConfig("user-2"));
    }
  });

  it("returns generated flag for legacy users with null avatarType", () => {
    const avatar = resolveUserAvatarData({ id: "user-3", avatarType: null });
    expect(avatar.type).toBe("flag");
  });

  it("falls back from teams to owner avatars", () => {
    const ownerAvatar = { type: "image" as const, url: "https://example.com/owner.jpg" };
    expect(resolveTeamAvatarData({ id: "team-1", avatarType: "owner" }, ownerAvatar)).toEqual(ownerAvatar);
  });

  it("prefers uploaded team logos over owner avatars", () => {
    expect(resolveTeamAvatarData(
      { id: "team-1", avatarType: "uploaded", logoUrl: "https://example.com/team.jpg" },
      { type: "image", url: "https://example.com/owner.jpg" }
    )).toEqual({ type: "image", url: "https://example.com/team.jpg" });
  });
});
