"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __async = (__this, __arguments, generator) => {
  return new Promise((resolve, reject) => {
    var fulfilled = (value) => {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    };
    var rejected = (value) => {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    };
    var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
    step((generator = generator.apply(__this, __arguments)).next());
  });
};
var Feedback_stories_exports = {};
__export(Feedback_stories_exports, {
  ArtificialFailureToShowcaseDecoratorBehaviorInCaseOfADevCausedError: () => ArtificialFailureToShowcaseDecoratorBehaviorInCaseOfADevCausedError,
  AutoGeneratedDataOnly: () => AutoGeneratedDataOnly,
  Like: () => Like,
  LikeFailure: () => LikeFailure,
  Liked: () => Liked,
  Primary: () => Primary,
  WithDeleteDialog: () => WithDeleteDialog,
  default: () => Feedback_stories_default
});
module.exports = __toCommonJS(Feedback_stories_exports);
var import_react_relay = require("react-relay");
var import_relay = require("@nova/react-test-utils/relay");
var import_relay_test_utils = require("relay-test-utils");
var import_test = require("@storybook/test");
var import_Feedback = require("./Feedback");
var import_schema = require("../../testing-utils/schema");
var React = __toESM(require("react"), 1);
const novaDecorator = (0, import_relay.getNovaDecorator)(import_schema.schema, {
  getEnvironmentOptions: () => ({
    storeOptions: {}
  }),
  // We add this to verify scenario of using relay's MockPayloadGenerator
  generateFunction: (operation, mockResolvers) => {
    const result = import_relay_test_utils.MockPayloadGenerator.generateWithDefer(
      operation,
      mockResolvers != null ? mockResolvers : null,
      {
        mockClientData: true,
        generateDeferredPayload: true
      }
    );
    return result;
  }
});
const meta = {
  component: import_Feedback.FeedbackComponent,
  decorators: [novaDecorator],
  parameters: {
    novaEnvironment: {
      query: import_react_relay.graphql`
        query FeedbackStoryRelayQuery($id: ID!) @relay_test_operation {
          feedback(id: $id) {
            ...Feedback_feedbackRelayFragment
          }
          viewData {
            ...Feedback_viewDataRelayFragment
          }
        }
      `,
      variables: { id: "42" },
      referenceEntries: {
        feedback: (data) => data == null ? void 0 : data.feedback,
        viewData: (data) => data == null ? void 0 : data.viewData
      },
      resolvers: {
        ViewData: () => ({
          viewDataField: "View data field",
          likeLabel: "Like",
          unlikeLabel: "Unlike",
          numberOfLikesLabel: "You have {count} likes"
        })
      }
    }
  }
};
var Feedback_stories_default = meta;
const AutoGeneratedDataOnly = {};
const Primary = {
  parameters: {
    novaEnvironment: {
      resolvers: {
        Feedback: () => sampleFeedback
      }
    }
  },
  play: (context) => __async(void 0, null, function* () {
    const container = (0, import_test.within)(context.canvasElement);
    yield container.findByText("Feedback from resolvers: Feedback title");
  })
};
const Liked = {
  parameters: {
    novaEnvironment: {
      resolvers: {
        Feedback: () => __spreadProps(__spreadValues({}, sampleFeedback), {
          doesViewerLike: true
        })
      }
    }
  }
};
const likeResolvers = {
  FeedbackLikeMutationResult: () => ({
    feedback: __spreadProps(__spreadValues({}, sampleFeedback), {
      doesViewerLike: true
    })
  })
};
const Like = {
  parameters: Primary.parameters,
  play: (context) => __async(void 0, null, function* () {
    const container = (0, import_test.within)(context.canvasElement);
    const likeButton = yield container.findByRole("button", { name: "Like" });
    yield import_test.userEvent.click(likeButton);
    const {
      graphql: { mock }
    } = (0, import_relay.getNovaEnvironmentForStory)(context);
    yield (0, import_test.waitFor)(() => __async(void 0, null, function* () {
      const operation = mock.getMostRecentOperation();
      yield (0, import_test.expect)(operation).toBeDefined();
    }));
    mock.resolveMostRecentOperation((operation) => {
      return import_relay_test_utils.MockPayloadGenerator.generate(operation, likeResolvers);
    });
    yield container.findByRole("button", { name: "Unlike" });
  })
};
const mockOnError = (0, import_test.fn)();
const ArtificialFailureToShowcaseDecoratorBehaviorInCaseOfADevCausedError = {
  parameters: {
    novaEnvironment: {
      enableQueuedMockResolvers: false
    },
    errorBoundary: {
      onError: mockOnError
    }
  },
  play: (context) => __async(void 0, null, function* () {
    const {
      graphql: { mock }
    } = (0, import_relay.getNovaEnvironmentForStory)(context);
    yield (0, import_test.waitFor)(() => __async(void 0, null, function* () {
      const operation = mock.getMostRecentOperation();
      yield (0, import_test.expect)(operation).toBeDefined();
    }));
    mock.rejectMostRecentOperation(new Error("Query failed"));
    yield (0, import_test.waitFor)(() => {
      (0, import_test.expect)(mockOnError).toHaveBeenCalledTimes(1);
    });
    const call = mockOnError.mock.calls[0];
    (0, import_test.expect)(call[0].message).toBe("Query failed");
  })
};
const LikeFailure = {
  parameters: {
    novaEnvironment: {
      enableQueuedMockResolvers: false
    }
  },
  play: (context) => __async(void 0, null, function* () {
    const container = (0, import_test.within)(context.canvasElement);
    const {
      graphql: { mock }
    } = (0, import_relay.getNovaEnvironmentForStory)(context);
    yield (0, import_test.waitFor)(() => __async(void 0, null, function* () {
      const operation2 = mock.getMostRecentOperation();
      yield (0, import_test.expect)(operation2).toBeDefined();
    }));
    const operation = mock.getMostRecentOperation();
    const operationName = (0, import_relay.getOperationName)(operation);
    const operationType = (0, import_relay.getOperationType)(operation);
    (0, import_test.expect)(operationName).toEqual("FeedbackStoryRelayQuery");
    (0, import_test.expect)(operationType).toEqual("query");
    mock.resolveMostRecentOperation((operation2) => {
      return import_relay_test_utils.MockPayloadGenerator.generate(
        operation2,
        {
          Feedback: () => sampleFeedback,
          ViewData: () => ({
            viewDataField: "View data field",
            likeLabel: "Like",
            unlikeLabel: "Unlike",
            numberOfLikesLabel: "You have {count} likes"
          })
        },
        { mockClientData: true }
      );
    });
    const likeButton = yield container.findByRole("button", {
      name: "Like"
    });
    import_test.userEvent.click(likeButton);
    yield (0, import_test.waitFor)(() => __async(void 0, null, function* () {
      const operation2 = mock.getMostRecentOperation();
      (0, import_test.expect)(operation2).toBeDefined();
    }));
    const nextOperation = mock.getMostRecentOperation();
    const nextOperationName = (0, import_relay.getOperationName)(nextOperation);
    const nextOperationType = (0, import_relay.getOperationType)(nextOperation);
    (0, import_test.expect)(nextOperationName).toEqual("FeedbackComponent_RelayLikeMutation");
    (0, import_test.expect)(nextOperationType).toEqual("mutation");
    mock.rejectMostRecentOperation(new Error("Like failed"));
    yield container.findByText("Something went wrong");
  })
};
const FeedbackWithDeleteDialog = (props) => {
  const [open, setOpen] = React.useState(false);
  const [text, setText] = React.useState("");
  return /* @__PURE__ */ React.createElement(
    import_relay.EventingInterceptor,
    {
      eventMap: {
        onDeleteFeedback: (eventWrapper) => {
          setOpen(true);
          setText(eventWrapper.event.data().feedbackText);
          return Promise.resolve(void 0);
        },
        feedbackTelemetry: (eventWrapper) => {
          console.log("Telemetry event", eventWrapper.event.data());
          return Promise.resolve(eventWrapper);
        }
      }
    },
    /* @__PURE__ */ React.createElement(import_Feedback.FeedbackComponent, __spreadValues({}, props)),
    /* @__PURE__ */ React.createElement("dialog", { open }, /* @__PURE__ */ React.createElement("button", { onClick: () => setOpen(false) }, "Cancel"), 'Are you sure you want to delete feedback "', text, '"')
  );
};
const WithDeleteDialog = __spreadProps(__spreadValues({}, Primary), {
  render: (args) => /* @__PURE__ */ React.createElement(FeedbackWithDeleteDialog, __spreadValues({}, args)),
  play: (context) => __async(void 0, null, function* () {
    const container = (0, import_test.within)(context.canvasElement);
    const deleteButton = yield container.findByRole("button", {
      name: "Delete feedback"
    });
    yield import_test.userEvent.click(deleteButton);
    const dialog = yield container.findByRole("dialog");
    yield (0, import_test.expect)(dialog).toBeInTheDocument();
  })
});
const sampleFeedback = {
  id: "42",
  message: {
    text: "Feedback title"
  },
  doesViewerLike: false,
  displayLabel: "Feedback from resolvers"
};
