// #region DashboardProfileOverrideIntegrationTest:Module [TYPE Function]
// @SEMANTICS: tests, dashboards, profile-filter, override, restore
// @PURPOSE: Verifies temporary show-all override and restore-on-return behavior for profile-default dashboard filtering.
// @LAYER UI (Tests)
// @RELATION DEPENDS_ON -> [EXT:frontend:DashboardHub]

import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor } from "@testing-library/svelte";
import { writable } from "svelte/store";

import DashboardsPage from "../+page.svelte";
import { api } from "$lib/api.js";
import { initializeEnvironmentContext } from "$lib/stores/environmentContext.svelte.js";

const mockedApi = /** @type {any} */ (api);
const mockedInitializeEnvironmentContext =
  /** @type {any} */ (initializeEnvironmentContext);

vi.mock("$lib/api.js", () => ({
  api: {
    getDashboards: vi.fn(),
    postApi: vi.fn(),
    getDatabaseMappings: vi.fn(),
    calculateMigrationDryRun: vi.fn(),
    getEnvironmentDatabases: vi.fn(),
  },
}));

vi.mock('$lib/toasts.svelte.js', () => ({
  addToast: vi.fn(),
}));

vi.mock("$lib/stores/taskDrawer.svelte.js", () => ({
  openDrawerForTask: vi.fn(),
}));

vi.mock("../../services/gitService.js", () => ({
  gitService: {
    getConfigs: vi.fn().mockResolvedValue([]),
    getStatusesBatch: vi.fn().mockResolvedValue({ statuses: {} }),
    initRepository: vi.fn(),
    sync: vi.fn(),
    commit: vi.fn(),
    pull: vi.fn(),
    push: vi.fn(),
  },
}));

vi.mock("$lib/stores/environmentContext.svelte.js", () => {
  const context = writable({
    environments: [{ id: "dev", name: "Development" }],
    selectedEnvId: "dev",
    isLoading: false,
    isLoaded: true,
    error: null,
  });

  return {
    environmentContextStore: { subscribe: context.subscribe },
    initializeEnvironmentContext: vi.fn().mockResolvedValue(undefined),
  };
});

vi.mock('$lib/i18n/index.svelte.js', () => ({
  t: {
    subscribe: (run) => {
      run({
        nav: { dashboards: "Dashboards" },
        common: {
          refresh: "Refresh",
          retry: "Retry",
          cancel: "Cancel",
          first: "First",
          last: "Last",
          loading: "Loading...",
          clear: "Clear",
          on: "On",
          off: "Off",
          close_modal: "Close modal",
        },
        dashboard: {
          empty: "No dashboards found",
          search: "Search dashboards...",
          title: "Title",
          llm_status: "LLM Validation Status",
          actions: "Actions",
          changed_on: "Changed On",
          owners: "Owners",
          select_all: "Select All",
          deselect_all: "Deselect All",
          select_visible: "Select Visible",
          deselect_visible: "Deselect Visible",
          selected_count: "{count} selected",
          column_filter: "Column filter",
          previous: "Previous",
          next: "Next",
          per_page_option: "{count} per page",
          showing: "Showing {start} to {end} of {total} dashboards",
        },
        profile: {
          filter_badge_active: "My Dashboards Only",
          filter_badge_override: "Showing all dashboards temporarily",
          filter_show_all_temporarily: "Show all dashboards temporarily",
          filter_restore_default: "Restore default filter",
          filter_empty_state:
            "No dashboards found for your account. Try adjusting your filter settings.",
        },
      });
      return () => {};
    },
  },
  _: vi.fn((key) => key),
}));

function buildFilteredResponse() {
  return {
    dashboards: [
      {
        id: 1,
        title: "Owner Dashboard",
        slug: "owner-dashboard",
        last_modified: "2026-03-04T10:00:00Z",
        owners: ["john_doe"],
        modified_by: "john_doe",
        git_status: {
          branch: "main",
          sync_status: "OK",
          has_repo: true,
          has_changes_for_commit: false,
        },
        last_task: null,
      },
    ],
    total: 1,
    page: 1,
    page_size: 10,
    total_pages: 1,
    effective_profile_filter: {
      applied: true,
      source_page: "dashboards_main",
      override_show_all: false,
      username: "john_doe",
      match_logic: "owners_or_modified_by",
    },
  };
}

function buildUnfilteredResponse() {
  return {
    dashboards: [
      {
        id: 1,
        title: "Owner Dashboard",
        slug: "owner-dashboard",
        last_modified: "2026-03-04T10:00:00Z",
        owners: ["john_doe"],
        modified_by: "john_doe",
        git_status: {
          branch: "main",
          sync_status: "OK",
          has_repo: true,
          has_changes_for_commit: false,
        },
        last_task: null,
      },
      {
        id: 2,
        title: "Team Dashboard",
        slug: "team-dashboard",
        last_modified: "2026-03-04T10:30:00Z",
        owners: ["analytics-team"],
        modified_by: "someone_else",
        git_status: {
          branch: "main",
          sync_status: "OK",
          has_repo: true,
          has_changes_for_commit: false,
        },
        last_task: null,
      },
    ],
    total: 2,
    page: 1,
    page_size: 10,
    total_pages: 1,
    effective_profile_filter: {
      applied: false,
      source_page: "dashboards_main",
      override_show_all: true,
      username: null,
      match_logic: null,
    },
  };
}

describe("dashboard-profile-override.integration", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockedApi.getDatabaseMappings.mockResolvedValue({ mappings: [] });
    mockedApi.getEnvironmentDatabases.mockResolvedValue([]);
    mockedApi.calculateMigrationDryRun.mockResolvedValue({
      summary: {
        dashboards: { create: 0, update: 0, delete: 0 },
        charts: { create: 0, update: 0, delete: 0 },
        datasets: { create: 0, update: 0, delete: 0 },
      },
    });
    mockedApi.postApi.mockResolvedValue({ task_id: "task-1" });
  });

  it("temporarily shows all dashboards and restores profile-default filter on return", async () => {
    // Track override state: the component may call getDashboards multiple times due
    // to reactive effects. Return the correct response based on current mode.
    let overrideShowAll = false;
    mockedApi.getDashboards.mockImplementation((_envId, opts) => {
      if (opts?.override_show_all === true) {
        overrideShowAll = true;
        return Promise.resolve(buildUnfilteredResponse());
      }
      overrideShowAll = false;
      return Promise.resolve(buildFilteredResponse());
    });

    const firstView = render(DashboardsPage);

    await waitFor(() => {
      expect(mockedInitializeEnvironmentContext).toHaveBeenCalledTimes(1);
    });

    // Wait until state stabilizes with filtered view
    await screen.findByText("My Dashboards Only");

    await fireEvent.click(
      screen.getByRole("button", { name: "Show all dashboards temporarily" }),
    );

    await screen.findByText("Showing all dashboards temporarily");

    firstView.unmount();

    // Simulate a fresh mount — the override should be cleared
    overrideShowAll = false;
    mockedApi.getDashboards.mockClear();
    mockedApi.getDashboards.mockImplementation((_envId, opts) => {
      if (opts?.override_show_all === true) {
        return Promise.resolve(buildUnfilteredResponse());
      }
      return Promise.resolve(buildFilteredResponse());
    });
    render(DashboardsPage);

    await screen.findByText("My Dashboards Only");
  });

  it("renders filtered empty state message when profile filter is active and no dashboards match", async () => {
    mockedApi.getDashboards.mockResolvedValue({
      dashboards: [],
      total: 0,
      page: 1,
      page_size: 10,
      total_pages: 1,
      effective_profile_filter: {
        applied: true,
        source_page: "dashboards_main",
        override_show_all: false,
        username: "john_doe",
        match_logic: "owners_or_modified_by",
      },
    });

    render(DashboardsPage);

    await screen.findByText(
      "No dashboards found for your account. Try adjusting your filter settings.",
    );
    expect(
      screen.getAllByRole("button", { name: "Show all dashboards temporarily" })
        .length,
    ).toBeGreaterThan(0);
  });
});

// #endregion DashboardProfileOverrideIntegrationTest:Module
