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

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

vi.mock("~/database/schema", () => ({
  seasonTemplateSports: "seasonTemplateSports",
  seasonTemplates: "seasonTemplates",
  seasonParticipants: "seasonParticipants",
  seasonSports: "seasonSports",
  sportsSeasons: {
    sportId: "sports_seasons.sport_id",
    name: "sports_seasons.name",
    year: "sports_seasons.year",
  },
  sports: {
    slug: "sports.slug",
  },
}));

vi.mock("drizzle-orm", () => ({
  and: (...args: unknown[]) => ({ type: "and", args }),
  eq: (col: unknown, val: unknown) => ({ type: "eq", col, val }),
}));

import { database } from "~/database/context";
import { importSportsDataFromJSON } from "../sports-data-sync.server";

function makeImportData(overrides: Record<string, unknown> = {}) {
  return JSON.stringify({
    version: "1.1",
    exportedAt: "2026-01-01T00:00:00.000Z",
    sports: [
      {
        name: "LLWS",
        type: "team",
        slug: "llws",
        description: "Little League World Series",
        ...overrides,
      },
    ],
    sportsSeasons: [],
    participants: [],
    seasonTemplates: [],
  });
}

function makeTx(existingSport: Record<string, unknown>) {
  const set = vi.fn().mockReturnThis();
  const where = vi.fn().mockReturnThis();
  return {
    query: {
      sports: {
        findFirst: vi.fn().mockResolvedValue(existingSport),
      },
    },
    update: vi.fn(() => ({ set, where })),
    insert: vi.fn(),
    delete: vi.fn(),
    set,
    where,
  };
}

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

describe("importSportsDataFromJSON", () => {
  it("preserves an existing public page exclusion during legacy merge imports", async () => {
    const tx = makeTx({ id: "sport-1", excludeFromHomepage: true });
    vi.mocked(database).mockReturnValue({
      transaction: vi.fn(async (callback) => callback(tx)),
    } as never);

    await importSportsDataFromJSON(makeImportData(), "merge");

    expect(tx.set).toHaveBeenCalledWith(expect.objectContaining({
      excludeFromHomepage: true,
    }));
  });

  it("applies an explicit public page exclusion value during merge imports", async () => {
    const tx = makeTx({ id: "sport-1", excludeFromHomepage: true });
    vi.mocked(database).mockReturnValue({
      transaction: vi.fn(async (callback) => callback(tx)),
    } as never);

    await importSportsDataFromJSON(makeImportData({ excludeFromHomepage: false }), "merge");

    expect(tx.set).toHaveBeenCalledWith(expect.objectContaining({
      excludeFromHomepage: false,
    }));
  });
});
