import { describe, expect, it, vi } from "vitest";
import { render } from "@testing-library/react";
import { FluentProvider, webLightTheme } from "@fluentui/react-components";

import { JailsTab } from "../JailsTab";
import type { JailConfig } from "../../../types/config";
import { useAutoSave } from "../../../hooks/useAutoSave";
import { useJailConfigs } from "../../../hooks/useConfig";
import { useConfigActiveStatus } from "../../../hooks/useConfigActiveStatus";

vi.mock("../../../hooks/useAutoSave");
vi.mock("../../../hooks/useConfig");
vi.mock("../../../hooks/useConfigActiveStatus");
vi.mock("../../../api/config", () => ({
  fetchInactiveJails: vi.fn().mockResolvedValue({ jails: [] }),
  deactivateJail: vi.fn(),
  deleteJailLocalOverride: vi.fn(),
  addLogPath: vi.fn(),
  deleteLogPath: vi.fn(),
  fetchJailConfigFileContent: vi.fn(),
  updateJailConfigFile: vi.fn(),
  validateJailConfig: vi.fn(),
}));

const mockUseAutoSave = vi.mocked(useAutoSave);
const mockUseJailConfigs = vi.mocked(useJailConfigs);
const mockUseConfigActiveStatus = vi.mocked(useConfigActiveStatus);

const basicJail: JailConfig = {
  name: "sshd",
  ban_time: 600,
  max_retry: 5,
  find_time: 600,
  fail_regex: [],
  ignore_regex: [],
  log_paths: [],
  date_pattern: null,
  log_encoding: "auto",
  backend: "polling",
  use_dns: "warn",
  prefregex: "",
  actions: [],
  bantime_escalation: null,
};

describe("JailsTab", () => {
  it("does not include backend in auto-save payload", () => {
    const autoSavePayloads: Array<Record<string, unknown>> = [];
    mockUseAutoSave.mockImplementation((value) => {
      autoSavePayloads.push(value as Record<string, unknown>);
      return { status: "idle", errorText: null, retry: vi.fn() };
    });

    mockUseJailConfigs.mockReturnValue({
      jails: [basicJail],
      total: 1,
      loading: false,
      error: null,
      refresh: vi.fn(),
      updateJail: vi.fn(),
      reloadAll: vi.fn(),
    });

    mockUseConfigActiveStatus.mockReturnValue({
      activeJails: new Set<string>(),
      activeFilters: new Set<string>(),
      activeActions: new Set<string>(),
      loading: false,
      error: null,
      refresh: vi.fn(),
    });

    render(
      <FluentProvider theme={webLightTheme}>
        <JailsTab initialJail="sshd" />
      </FluentProvider>,
    );

    expect(autoSavePayloads.length).toBeGreaterThan(0);
    const lastPayload = autoSavePayloads[autoSavePayloads.length - 1];

    expect(lastPayload).not.toHaveProperty("backend");
  });
});
