// [DEF:frontend.src.routes.profile.__tests__.profile_preferences_integration:Module]
// @TIER: STANDARD
// @SEMANTICS: tests, profile, integration, lookup, persistence, fallback
// @PURPOSE: Verifies profile binding happy path and degraded lookup manual fallback save flow.
// @LAYER: UI (Tests)
// @RELATION: TESTS -> frontend/src/routes/profile/+page.svelte

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

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

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

vi.mock("$lib/api.js", () => ({
  api: {
    getProfilePreferences: vi.fn(),
    lookupSupersetAccounts: vi.fn(),
    updateProfilePreferences: vi.fn(),
  },
}));

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

vi.mock("$lib/stores/environmentContext.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", () => ({
  t: {
    subscribe: (run) => {
      run({
        common: { cancel: "Cancel" },
        profile: {
          title: "Profile",
          description: "Manage your profile preferences, Git integration, and access view.",
          dashboard_preferences: "Dashboard Preferences",
          superset_environment: "Superset Environment",
          superset_environment_placeholder: "Select environment",
          superset_account: "Your Apache Superset Account",
          superset_account_placeholder: "Enter your Apache Superset username",
          lookup_loading: "Loading Superset accounts...",
          lookup_error:
            "Cannot load Superset accounts for this environment right now. You can enter username manually.",
          lookup_button: "Lookup",
          lookup_search_placeholder: "Search account candidates",
          lookup_no_results:
            "No account candidates found. You can enter username manually.",
          show_only_my_dashboards: "Show only my dashboards by default",
          show_only_slug_dashboards: "Show only dashboards with slug by default",
          save_preferences: "Save Preferences",
          save_success: "Preferences saved",
          save_error: "Failed to save preferences. Please try again.",
        },
      });
      return () => {};
    },
  },
  _: vi.fn((key) => key),
}));

describe("profile-preferences.integration", () => {
  beforeEach(() => {
    vi.clearAllMocks();

    mockedApi.getProfilePreferences.mockResolvedValue({
      status: "success",
      preference: {
        user_id: "u-1",
        superset_username: null,
        show_only_my_dashboards: false,
        show_only_slug_dashboards: true,
        git_username: null,
        git_email: null,
        has_git_personal_access_token: false,
        git_personal_access_token_masked: null,
        email_address: null,
        telegram_id: null,
        notify_on_fail: true,
        start_page: "dashboards",
        auto_open_task_drawer: true,
        dashboards_table_density: "comfortable",
      },
      security: {
        read_only: true,
        auth_source: "adfs",
        current_role: "Data Engineer",
        role_source: "adfs",
        roles: ["Data Engineer"],
        permissions: [],
      },
    });

    mockedApi.updateProfilePreferences.mockResolvedValue({
      status: "success",
      preference: {
        user_id: "u-1",
        superset_username: "john_doe",
        show_only_my_dashboards: true,
        show_only_slug_dashboards: true,
        git_username: null,
        git_email: null,
        has_git_personal_access_token: false,
        git_personal_access_token_masked: null,
        email_address: null,
        telegram_id: null,
        notify_on_fail: true,
        start_page: "dashboards",
        auto_open_task_drawer: true,
        dashboards_table_density: "comfortable",
      },
      security: {
        read_only: true,
        auth_source: "adfs",
        current_role: "Data Engineer",
        role_source: "adfs",
        roles: ["Data Engineer"],
        permissions: [],
      },
    });
  });

  it("binds account from lookup and saves enabled default filter", async () => {
    mockedApi.lookupSupersetAccounts.mockResolvedValue({
      status: "success",
      environment_id: "dev",
      page_index: 0,
      page_size: 20,
      total: 1,
      items: [
        {
          environment_id: "dev",
          username: "john_doe",
          display_name: "John Doe",
          email: "john@example.local",
          is_active: true,
        },
      ],
    });

    render(ProfilePage);

    await waitFor(() => {
      expect(mockedInitializeEnvironmentContext).toHaveBeenCalledTimes(1);
      expect(mockedApi.getProfilePreferences).toHaveBeenCalledTimes(1);
      expect(mockedApi.lookupSupersetAccounts).toHaveBeenCalled();
    });

    await fireEvent.click(await screen.findByText("John Doe"));

    const usernameInput = /** @type {HTMLInputElement} */ (
      screen.getByPlaceholderText("Enter your Apache Superset username")
    );
    expect(usernameInput.value).toBe("john_doe");

    const toggle = screen.getByLabelText("Show only my dashboards by default");
    await fireEvent.click(toggle);

    await fireEvent.click(
      screen.getByRole("button", { name: "Save Preferences" }),
    );

    await waitFor(() => {
      expect(mockedApi.updateProfilePreferences).toHaveBeenCalledWith({
        superset_username: "john_doe",
        show_only_my_dashboards: true,
        show_only_slug_dashboards: true,
        git_username: null,
        git_email: null,
        email_address: null,
        telegram_id: null,
        notify_on_fail: true,
        start_page: "dashboards",
        auto_open_task_drawer: true,
        dashboards_table_density: "comfortable",
      });
      expect(mockedAddToast).toHaveBeenCalledWith("Preferences saved", "success");
    });
  });

  it("keeps manual save available when lookup fails (degraded fallback)", async () => {
    mockedApi.lookupSupersetAccounts.mockRejectedValue(
      new Error("lookup unavailable"),
    );
    mockedApi.updateProfilePreferences.mockResolvedValue({
      status: "success",
      preference: {
        user_id: "u-1",
        superset_username: "manual_user",
        show_only_my_dashboards: true,
        show_only_slug_dashboards: true,
        git_username: null,
        git_email: null,
        has_git_personal_access_token: false,
        git_personal_access_token_masked: null,
        email_address: null,
        telegram_id: null,
        notify_on_fail: true,
        start_page: "dashboards",
        auto_open_task_drawer: true,
        dashboards_table_density: "comfortable",
      },
      security: {
        read_only: true,
        auth_source: "adfs",
        current_role: "Data Engineer",
        role_source: "adfs",
        roles: ["Data Engineer"],
        permissions: [],
      },
    });

    render(ProfilePage);

    await waitFor(() => {
      expect(mockedApi.lookupSupersetAccounts).toHaveBeenCalled();
    });

    await screen.findByText(
      "Cannot load Superset accounts for this environment right now. You can enter username manually.",
    );

    const usernameInput = screen.getByPlaceholderText(
      "Enter your Apache Superset username",
    );
    await fireEvent.input(usernameInput, { target: { value: "manual_user" } });

    const toggle = screen.getByLabelText("Show only my dashboards by default");
    await fireEvent.click(toggle);

    await fireEvent.click(
      screen.getByRole("button", { name: "Save Preferences" }),
    );

    await waitFor(() => {
      expect(mockedApi.updateProfilePreferences).toHaveBeenCalledWith({
        superset_username: "manual_user",
        show_only_my_dashboards: true,
        show_only_slug_dashboards: true,
        git_username: null,
        git_email: null,
        email_address: null,
        telegram_id: null,
        notify_on_fail: true,
        start_page: "dashboards",
        auto_open_task_drawer: true,
        dashboards_table_density: "comfortable",
      });
    });
  });
});

// [/DEF:frontend.src.routes.profile.__tests__.profile_preferences_integration:Module]
