/**
 * @vitest-environment jsdom
 */
// @ts-nocheck
// #region DatasetReviewUs3UxTests:Module [TYPE Function]
// @SEMANTICS: dataset-review, execution, mapping, preview, launch, ux-tests
// @PURPOSE: Verify US3 mapping review, Superset preview, and launch confirmation UX contracts.
// @LAYER UI
// @RELATION DEPENDS_ON -> [ExecutionMappingReview]
// @RELATION DEPENDS_ON -> [CompiledSQLPreview]
// @RELATION DEPENDS_ON -> [LaunchConfirmationPanel]
// @UX_STATE: WarningApproval -> Mapping review requires explicit approval or manual override.
// @UX_STATE: Ready -> Preview and launch panels expose reviewed Superset-backed execution context.
// @UX_STATE: Blocked -> Launch panel lists blockers instead of allowing hidden bypass.
// @TEST_CONTRACT: Us3ExecutionProps -> ObservableExecutionUx
// @TEST_SCENARIO: mapping_review_approves_warning_sensitive_row -> Approval persists and keeps blockers visible until cleared.
// @TEST_SCENARIO: preview_panel_requests_superset_compilation_and_renders_sql -> Preview stays explicitly Superset-derived.
// @TEST_SCENARIO: launch_panel_blocks_then_submits_sql_lab_launch -> Launch lists gates first and shows audited handoff after success.
// @TEST_EDGE: missing_field -> Missing preview or run context remains readable.
// @TEST_EDGE: external_fail -> Failed preview request surfaces inline error.
// @TEST_EDGE: invalid_type -> Mixed values stringify without crashing.
// @TEST_INVARIANT: execution_gates_remain_visible -> VERIFIED_BY: [mapping_review_approves_warning_sensitive_row, preview_panel_requests_superset_compilation_and_renders_sql, launch_panel_blocks_then_submits_sql_lab_launch]

import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/svelte";
import { requestDatasetReviewApi } from "$lib/api/datasetReview.js";
import ExecutionMappingReview from "../ExecutionMappingReview.svelte";
import CompiledSQLPreview from "../CompiledSQLPreview.svelte";
import LaunchConfirmationPanel from "../LaunchConfirmationPanel.svelte";

vi.mock("$lib/api/datasetReview.js", () => ({
  requestDatasetReviewApi: vi.fn(),
}));

vi.mock('$lib/i18n/index.svelte.js', () => ({
  t: {
    subscribe: (fn) => {
      fn({
        common: {
          error: "Common error",
          cancel: "Cancel",
          not_available: "N/A",
          unknown: "Unknown",
        },
        dataset_review: {
          mapping: {
            eyebrow: "Template mapping",
            title: "Review filter-to-template mappings",
            description: "Verify imported filter values, effective execution values, and warning-sensitive transformations before preview or launch.",
            state_label: "Mapping state",
            state: {
              Incomplete: "Incomplete",
              WarningApproval: "Approval required",
              Approved: "Approved",
            },
            pending_approvals_label: "Pending approvals",
            required_values_label: "Missing required values",
            empty: "No execution mappings are available yet.",
            required_blockers_notice: "{count} required values still need attention before preview or launch can proceed.",
            approval_notice: "{count} mapping transformations still need explicit approval.",
            to_variable_label: "To variable",
            required_badge: "Required",
            approval_required_badge: "Approval required",
            approved_badge: "Approved",
            source_filter_label: "Source filter",
            source_value_label: "Source value",
            confidence_label: "Confidence",
            recovery_label: "Recovery",
            effective_value_label: "Effective value",
            method_label: "Method",
            approval_label: "Approval",
            warning_label: "Warning",
            transformation_note_label: "Transformation note",
            missing_required_value: "This mapping still lacks a required effective value.",
            manual_value_label: "Manual effective value",
            manual_note_label: "Manual override note",
            save_override_action: "Save manual override",
            manual_override_action: "Manual override",
            approve_action: "Approve mapping",
            approve_all_action: "Approve all pending mappings",
            approval_state: {
              pending: "Pending",
              approved: "Approved",
              rejected: "Rejected",
              not_required: "Not required",
            },
            warning_level: {
              none: "None",
              low: "Low",
              medium: "Medium",
              high: "High",
            },
            method: {
              direct_match: "Direct match",
              heuristic_match: "Heuristic match",
              semantic_match: "Semantic match",
              manual_override: "Manual override",
            },
            messages: {
              saving: "Saving mapping decision...",
              approval_saved: "Mapping approval recorded.",
              approval_failed: "Failed to save mapping approval.",
              override_saved: "Manual mapping override saved. Preview should be refreshed.",
              override_failed: "Failed to save manual mapping override.",
              required_value_missing: "Provide a required value before saving the manual override.",
            },
          },
          preview: {
            eyebrow: "Compiled SQL preview",
            title: "Review Superset-compiled SQL",
            description: "Preview truth comes only from Superset. Regenerate the preview whenever mappings or required inputs change.",
            state_label: "Preview state",
            state: {
              missing: "Missing",
              pending: "Pending",
              ready: "Ready",
              stale: "Stale",
              failed: "Error",
            },
            generate_action: "Generate SQL preview",
            generate_loading: "Generating preview...",
            missing_body: "No Superset preview is available yet. Generate one before attempting launch.",
            pending_body: "Superset is compiling the current execution context. Launch stays blocked until preview completes.",
            ready_body: "This SQL preview was compiled by Superset for the current execution inputs.",
            stale_body: "Mappings or effective values changed after the last successful preview. Regenerate before launch.",
            error_body: "Superset could not compile the current execution context.",
            compiler_label: "Compiled source",
            compiled_by_superset: "Compiled by Superset",
            compiled_source_unknown: "Compilation source unavailable",
            fingerprint_label: "Preview fingerprint",
            compiled_at_label: "Compiled at",
            sql_block_title: "Superset SQL",
            compiled_truth_note: "Exact SQL returned by Superset",
            go_to_mapping_action: "Review mapping inputs",
            review_inputs_action: "Review changed inputs",
            messages: {
              generated: "Superset preview refreshed.",
              generate_failed: "Failed to generate Superset preview.",
            },
          },
          launch: {
            eyebrow: "Launch confirmation",
            title: "Confirm SQL Lab launch",
            description: "Launch remains blocked until preview truth, approvals, and readiness gates all match the reviewed execution context.",
            state_label: "Launch state",
            state: {
              Blocked: "Blocked",
              Ready: "Ready",
              Submitted: "Submitted",
            },
            blocked_title: "Launch blockers",
            blocked_body: "Resolve the items below before sending this dataset run to SQL Lab.",
            resolve_action: "Open related area",
            dataset_ref_label: "Dataset reference",
            readiness_label: "Readiness",
            approved_mappings_label: "Approved mappings",
            preview_fingerprint_label: "Preview fingerprint",
            sql_lab_target_title: "Launch target",
            sql_lab_target_body: "The canonical launch target is a Superset SQL Lab session using the reviewed preview and effective execution inputs.",
            preview_status_label: "Preview status",
            compiled_by_label: "Compiled by",
            launch_action: "Launch dataset",
            launch_loading: "Launching dataset...",
            submitted_title: "Launch submitted",
            submitted_body: "SQL Lab handoff and audited run context were recorded for this launch request.",
            run_context_label: "Run context",
            sql_lab_session_label: "SQL Lab session",
            launch_status_label: "Launch status",
            preview_ref_label: "Preview reference",
            blockers: {
              blocking_finding: "Blocking findings remain unresolved",
              mapping_approval_required: "Mapping approval is still required",
              preview_missing: "Superset preview is required before launch",
              preview_pending: "Preview generation is still in progress",
              preview_stale: "Preview no longer matches the current execution inputs",
              preview_failed: "Preview failed and launch remains blocked",
              readiness_not_run_ready: "Session is not yet in run-ready state",
              preview_fingerprint_missing: "Preview fingerprint is missing, so launch cannot be trusted",
            },
            messages: {
              launch_started: "Dataset launch request sent to SQL Lab.",
              launch_failed: "Failed to launch dataset in SQL Lab.",
            },
          },
        },
      });
      return () => {};
    },
  },
}));

describe("Dataset review US3 execution UX", () => {
  beforeEach(() => {
    requestDatasetReviewApi.mockReset();
  });

  it("mapping_review_approves_warning_sensitive_row", async () => {
    requestDatasetReviewApi.mockResolvedValueOnce({
      mapping_id: "map-1",
      filter_id: "filter-1",
      variable_id: "var-1",
      mapping_method: "direct_match",
      raw_input_value: "DE",
      effective_value: "DE",
      transformation_note: "Trimmed imported value",
      warning_level: "medium",
      requires_explicit_approval: true,
      approval_state: "approved",
    });

    const onupdated = vi.fn();

    render(ExecutionMappingReview, {
      sessionId: "session-1",
      mappings: [
        {
          mapping_id: "map-1",
          filter_id: "filter-1",
          variable_id: "var-1",
          mapping_method: "direct_match",
          raw_input_value: "DE",
          effective_value: "DE",
          transformation_note: "Trimmed imported value",
          warning_level: "medium",
          requires_explicit_approval: true,
          approval_state: "pending",
        },
      ],
      importedFilters: [
        {
          filter_id: "filter-1",
          filter_name: "country",
          display_name: "Country",
          raw_value: "DE",
          normalized_value: "DE",
          confidence_state: "imported",
          recovery_status: "recovered",
        },
      ],
      templateVariables: [
        {
          variable_id: "var-1",
          variable_name: "country",
          is_required: true,
          default_value: null,
        },
      ],
      onupdated,
    });

    expect(screen.getByText("Review filter-to-template mappings")).toBeDefined();
    expect(screen.getByText("Approval required")).toBeDefined();
    expect(screen.getByText("Country")).toBeDefined();
    expect(screen.getByText(/Trimmed imported value/)).toBeDefined();

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

    await waitFor(() => {
      expect(requestDatasetReviewApi).toHaveBeenCalledWith(
        "/dataset-orchestration/sessions/session-1/mappings/map-1/approve",
        "POST",
        { approval_note: "Trimmed imported value" },
        null,
      );
    });

    expect(onupdated).toHaveBeenCalledWith({
      mapping: expect.objectContaining({
        mapping_id: "map-1",
        approval_state: "approved",
      }),
      preview_state: "unchanged",
    });
    expect(screen.getByText("Mapping approval recorded.")).toBeDefined();
  });

  it("mapping_review_batch_approves_pending_rows", async () => {
    requestDatasetReviewApi.mockResolvedValueOnce([
      {
        mapping_id: "map-1",
        filter_id: "filter-1",
        variable_id: "var-1",
        mapping_method: "direct_match",
        raw_input_value: "DE",
        effective_value: "DE",
        transformation_note: "Trimmed imported value",
        warning_level: "medium",
        requires_explicit_approval: true,
        approval_state: "approved",
      },
    ]);

    const onupdated = vi.fn();

    render(ExecutionMappingReview, {
      sessionId: "session-1",
      mappings: [
        {
          mapping_id: "map-1",
          filter_id: "filter-1",
          variable_id: "var-1",
          mapping_method: "direct_match",
          raw_input_value: "DE",
          effective_value: "DE",
          transformation_note: "Trimmed imported value",
          warning_level: "medium",
          requires_explicit_approval: true,
          approval_state: "pending",
        },
      ],
      importedFilters: [
        {
          filter_id: "filter-1",
          filter_name: "country",
          display_name: "Country",
          raw_value: "DE",
          normalized_value: "DE",
          confidence_state: "imported",
          recovery_status: "recovered",
        },
      ],
      templateVariables: [
        {
          variable_id: "var-1",
          variable_name: "country",
          is_required: true,
          default_value: null,
        },
      ],
      onupdated,
    });

    await fireEvent.click(screen.getByRole("button", { name: "Approve all pending mappings" }));

    await waitFor(() => {
      expect(requestDatasetReviewApi).toHaveBeenCalledWith(
        "/dataset-orchestration/sessions/session-1/mappings/approve-batch",
        "POST",
        { mapping_ids: ["map-1"] },
        null,
      );
    });

    expect(onupdated).toHaveBeenCalledWith({
      mappings: expect.any(Array),
      preview_state: "unchanged",
    });
  });

  it("preview_panel_requests_superset_compilation_and_renders_sql", async () => {
    requestDatasetReviewApi.mockResolvedValueOnce({
      preview_id: "preview-1",
      session_id: "session-1",
      preview_status: "ready",
      compiled_sql: "SELECT * FROM sales WHERE country = 'DE'",
      preview_fingerprint: "fingerprint-1",
      compiled_by: "superset",
      compiled_at: "2026-03-17T09:00:00Z",
    });

    const onupdated = vi.fn();

    render(CompiledSQLPreview, {
      sessionId: "session-1",
      preview: null,
      previewState: "missing",
      onupdated,
    });

    expect(screen.getByText("Review Superset-compiled SQL")).toBeDefined();
    expect(screen.getByText("No Superset preview is available yet. Generate one before attempting launch.")).toBeDefined();

    await fireEvent.click(screen.getByRole("button", { name: "Generate SQL preview" }));

    await waitFor(() => {
      expect(requestDatasetReviewApi).toHaveBeenCalledWith(
        "/dataset-orchestration/sessions/session-1/preview",
        "POST",
        null,
        null,
      );
    });

    await waitFor(() => {
      expect(onupdated).toHaveBeenCalledWith({
        preview: expect.objectContaining({
          preview_id: "preview-1",
          compiled_by: "superset",
        }),
        preview_state: "ready",
      });
    });

    requestDatasetReviewApi.mockRejectedValueOnce(new Error("Superset compile failed"));

    const onjump = vi.fn();
    render(CompiledSQLPreview, {
      sessionId: "session-1",
      preview: {
        preview_id: "preview-err",
        preview_status: "failed",
        preview_fingerprint: "fingerprint-err",
        compiled_by: "superset",
        error_details: "Variable country is invalid",
      },
      previewState: "failed",
      onjump,
    });

    expect(screen.getByText("Variable country is invalid")).toBeDefined();

    await fireEvent.click(screen.getByRole("button", { name: "Review mapping inputs" }));
    expect(onjump).toHaveBeenCalledWith({ target: "mapping" });
  });

  it("launch_panel_blocks_then_submits_sql_lab_launch", async () => {
    const onjump = vi.fn();
    const { rerender } = render(LaunchConfirmationPanel, {
      sessionId: "session-1",
      session: {
        dataset_ref: "public.sales",
        readiness_state: "mapping_review_needed",
      },
      findings: [
        {
          severity: "blocking",
          resolution_state: "open",
          title: "Missing required value",
          message: "country is required",
          code: "REQ_COUNTRY",
        },
      ],
      mappings: [
        {
          mapping_id: "map-1",
          requires_explicit_approval: true,
          approval_state: "pending",
          transformation_note: "Europe -> EU",
        },
      ],
      preview: null,
      previewState: "missing",
      onjump,
    });

    expect(screen.getByText("Launch blockers")).toBeDefined();
    expect(screen.getByText("Blocking findings remain unresolved")).toBeDefined();
    expect(screen.getByText("Mapping approval is still required")).toBeDefined();
    expect(screen.getByText("Superset preview is required before launch")).toBeDefined();

    await fireEvent.click(screen.getAllByRole("button", { name: "Open related area" })[1]);
    expect(onjump).toHaveBeenCalledWith({ target: "mapping" });

    requestDatasetReviewApi.mockResolvedValueOnce({
      run_context: {
        run_context_id: "run-1",
        sql_lab_session_ref: "sql-lab-77",
        launch_status: "started",
        preview_id: "preview-1",
      },
    });

    await rerender({
      sessionId: "session-1",
      session: {
        dataset_ref: "public.sales",
        readiness_state: "run_ready",
      },
      findings: [],
      mappings: [
        {
          mapping_id: "map-1",
          requires_explicit_approval: true,
          approval_state: "approved",
          transformation_note: "Europe -> EU",
        },
      ],
      preview: {
        preview_id: "preview-1",
        preview_status: "ready",
        preview_fingerprint: "fingerprint-1",
        compiled_by: "superset",
      },
      previewState: "ready",
      onupdated: vi.fn(),
      onjump,
    });

    expect(screen.getByText("Confirm SQL Lab launch")).toBeDefined();
    expect(screen.getByText("Launch state: Ready")).toBeDefined();

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

    await waitFor(() => {
      expect(requestDatasetReviewApi).toHaveBeenCalledWith(
        "/dataset-orchestration/sessions/session-1/launch",
        "POST",
        null,
        null,
      );
    });

    expect(screen.getByText("Dataset launch request sent to SQL Lab.")).toBeDefined();
  });
});
// #endregion DatasetReviewUs3UxTests:Module
