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

vi.mock("~/database/context", () => ({
  database: vi.fn(),
}));

import { findAllSportsSeasons, findDraftableSportsSeasons } from "../sports-season";
import { database } from "~/database/context";

const mockSeasons = [
  { id: "season-1", name: "2025 NBA Playoffs", isDraftable: true, year: 2025 },
  { id: "season-2", name: "2025 F1 Season", isDraftable: true, year: 2025 },
  { id: "season-3", name: "2024 Old Golf", isDraftable: false, year: 2024 },
];

function makeMockDb(seasons: typeof mockSeasons) {
  return {
    query: {
      sportsSeasons: {
        findMany: vi.fn().mockResolvedValue(seasons),
      },
    },
  };
}

beforeEach(() => {
  vi.clearAllMocks();
});

describe("findAllSportsSeasons", () => {
  it("returns all sport seasons regardless of isDraftable", async () => {
    vi.mocked(database).mockReturnValue(makeMockDb(mockSeasons) as never);
    const result = await findAllSportsSeasons();
    expect(result).toHaveLength(3);
  });
});

describe("findDraftableSportsSeasons", () => {
  it("passes isDraftable=true filter to the query", async () => {
    const draftableOnly = mockSeasons.filter((s) => s.isDraftable);
    const mockDb = makeMockDb(draftableOnly);
    vi.mocked(database).mockReturnValue(mockDb as never);

    const result = await findDraftableSportsSeasons();
    expect(result).toHaveLength(2);
    expect(result.every((s) => s.isDraftable)).toBe(true);
  });

  it("returns empty array when no draftable seasons exist", async () => {
    vi.mocked(database).mockReturnValue(makeMockDb([]) as never);
    const result = await findDraftableSportsSeasons();
    expect(result).toHaveLength(0);
  });

  it("calls findMany with isDraftable where clause", async () => {
    const mockDb = makeMockDb([]);
    vi.mocked(database).mockReturnValue(mockDb as never);

    await findDraftableSportsSeasons();
    expect(mockDb.query.sportsSeasons.findMany).toHaveBeenCalledWith(
      expect.objectContaining({
        where: expect.anything(),
      })
    );
  });
});
