var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { createTheme } from '@mui/material/styles';
import { ThemeProvider } from '@mui/styles';
import { ActivityFilter, exportData, ExportDataFormat, ExportHeaderOrder } from '@reltio/mdm-sdk';
import { SnackbarContext } from '../contexts/SnackbarContext';
import { ExportDialog } from '../ExportDialog';
import { MdmModuleProvider } from '../contexts/MdmModuleContext';
import { ErrorPopup } from '../ErrorPopup';
import { theme } from '../constants';
jest.mock('@reltio/mdm-sdk', function () { return (__assign(__assign({}, jest.requireActual('@reltio/mdm-sdk')), { exportData: jest.fn() })); });
var metadata = {
    entityTypes: [
        {
            uri: 'configuration/entityTypes/HCP',
            label: 'HCP',
            attributes: [
                {
                    uri: 'configuration/entityTypes/HCP/attributes/FirstName',
                    type: 'String',
                    name: 'FirstName',
                    label: 'First Name',
                    access: ['READ', 'CREATE', 'UPDATE', 'INITIATE_CHANGE_REQUEST']
                },
                {
                    uri: 'configuration/entityTypes/HCP/attributes/LastName',
                    type: 'String',
                    name: 'LastName',
                    label: 'Last Name',
                    access: ['READ', 'CREATE', 'UPDATE', 'INITIATE_CHANGE_REQUEST']
                },
                {
                    uri: 'configuration/entityTypes/HCP/attributes/Phone',
                    type: 'String',
                    name: 'Phone',
                    label: 'Phone',
                    access: ['READ', 'CREATE', 'UPDATE', 'INITIATE_CHANGE_REQUEST']
                }
            ]
        },
        {
            uri: 'configuration/entityTypes/HCO',
            label: 'HCO',
            attributes: [
                {
                    label: 'Name',
                    name: 'Name',
                    type: 'String',
                    uri: 'configuration/entityTypes/HCO/attributes/Name'
                },
                {
                    label: 'Status',
                    name: 'Status',
                    type: 'String',
                    uri: 'configuration/entityTypes/HCO/attributes/Status'
                }
            ]
        }
    ]
};
var mdmValues = {
    metadata: metadata,
    exportPath: '/nui/export',
    tenant: {
        id: 't1',
        name: 't1'
    }
};
var mdmActions = { openConsoleApp: jest.fn() };
var defaultProps = {
    open: true,
    onClose: jest.fn(),
    columnsByEntityType: {
        'configuration/entityTypes/HCP': ['attributes.FirstName', 'attributes.LastName'],
        'configuration/entityTypes/HCO': []
    },
    profilesCount: 15,
    onExternalExport: jest.fn(),
    onLoadingChange: jest.fn(),
    filter: "(equals(type,'configuration/entityTypes/HCP') or equals(type,'configuration/entityTypes/HCO'))",
    activityFilter: ActivityFilter.ALL,
    isSearchByOv: true
};
var showSnackbarMessage = jest.fn();
var setUp = function (props) {
    if (props === void 0) { props = defaultProps; }
    var user = userEvent.setup();
    var Providers = function (_a) {
        var children = _a.children;
        return (React.createElement(ThemeProvider, { theme: createTheme(theme) },
            React.createElement(SnackbarContext.Provider, { value: showSnackbarMessage },
                React.createElement(MdmModuleProvider, { values: mdmValues, actions: mdmActions },
                    React.createElement(ErrorPopup, null),
                    children))));
    };
    return __assign(__assign({}, render(React.createElement(ExportDialog, __assign({}, props)), { wrapper: Providers })), { user: user });
};
describe('ExportDialog tests', function () {
    beforeEach(function () {
        exportData.mockResolvedValue({ status: 'scheduled' });
    });
    afterEach(function () {
        jest.clearAllMocks();
    });
    it('should render dialog correctly', function () {
        jest.useFakeTimers();
        jest.setSystemTime(new Date(2025, 10, 25, 9, 10, 0));
        setUp();
        expect(screen.getByRole('dialog')).toBeInTheDocument();
        expect(screen.getByLabelText('Export')).toBeInTheDocument();
        expect(screen.getByText('Name your export')).toBeInTheDocument();
        expect(screen.getByDisplayValue('Untitled Export Job 11252025_09:10')).toBeInTheDocument();
        expect(screen.getByText('Data selected')).toBeInTheDocument();
        expect(screen.getByText('15')).toBeInTheDocument();
        expect(screen.getByText('Profiles')).toBeInTheDocument();
        expect(screen.getByText('HCP')).toBeInTheDocument();
        expect(screen.getByText('(2/13 attributes),')).toBeInTheDocument();
        expect(screen.getByText('HCO')).toBeInTheDocument();
        expect(screen.getByText('(12/12 attributes)')).toBeInTheDocument();
        expect(screen.getByText('Export options')).toBeInTheDocument();
        expect(screen.getByText('File format')).toBeInTheDocument();
        expect(screen.getByText('CSV Flattened')).toBeInTheDocument();
        expect(screen.getByText('Export Operational Values (OV) only')).toBeInTheDocument();
        expect(screen.getByText('Only those attribute values that are selected by the survivorship rules will be exported')).toBeInTheDocument();
        expect(screen.getByRole('checkbox', { name: 'Export Operational Values (OV) only' })).not.toBeChecked();
        expect(screen.getByText('Want more export options?')).toBeInTheDocument();
        expect(screen.getByRole('button', { name: 'Go to export application' })).toBeInTheDocument();
        expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument();
        expect(screen.getByRole('button', { name: 'Export' })).toBeInTheDocument();
        jest.useRealTimers();
    });
    it('should call onClose when Cancel button is clicked', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp().user;
                    return [4 /*yield*/, user.click(screen.getByRole('button', { name: 'Cancel' }))];
                case 1:
                    _a.sent();
                    expect(defaultProps.onClose).toHaveBeenCalled();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onExternalExport when Go to export application button is clicked', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp().user;
                    return [4 /*yield*/, user.click(screen.getByRole('button', { name: 'Go to export application' }))];
                case 1:
                    _a.sent();
                    expect(defaultProps.onExternalExport).toHaveBeenCalledWith(false);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should pass exportOvOnly true to onExternalExport when OV checkbox is checked', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp().user;
                    return [4 /*yield*/, user.click(screen.getByRole('checkbox', { name: 'Export Operational Values (OV) only' }))];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getByRole('button', { name: 'Go to export application' }))];
                case 2:
                    _a.sent();
                    expect(defaultProps.onExternalExport).toHaveBeenCalledWith(true);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onExport once and shows snackbar action on success', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    jest.useFakeTimers();
                    jest.setSystemTime(new Date(2025, 10, 25, 9, 10, 0));
                    user = setUp().user;
                    jest.useRealTimers();
                    return [4 /*yield*/, user.click(screen.getByRole('button', { name: 'Export' }))];
                case 1:
                    _a.sent();
                    expect(defaultProps.onLoadingChange).toHaveBeenCalledWith(true);
                    expect(exportData).toHaveBeenCalledTimes(2);
                    expect(exportData).toHaveBeenCalledWith(expect.objectContaining({
                        exportPath: '/nui/export',
                        tenant: 't1',
                        options: {
                            fileFormat: ExportDataFormat.CSV,
                            dateFormat: 'readable',
                            activeness: ActivityFilter.ALL,
                            options: 'parallelExecution,searchByOv',
                            name: 'Untitled Export Job 11252025_09:10_HCP',
                            select: 'attributes.FirstName,attributes.LastName'
                        },
                        includeType: ['configuration/entityTypes/HCP'],
                        headerOrder: ExportHeaderOrder.Select,
                        filter: defaultProps.filter,
                        ovOnly: false
                    }));
                    expect(exportData).toHaveBeenCalledWith(expect.objectContaining({
                        exportPath: '/nui/export',
                        tenant: 't1',
                        options: {
                            fileFormat: ExportDataFormat.CSV,
                            dateFormat: 'readable',
                            activeness: ActivityFilter.ALL,
                            options: 'parallelExecution,searchByOv',
                            name: 'Untitled Export Job 11252025_09:10_entities',
                            sendHidden: false
                        },
                        includeType: ['configuration/entityTypes/HCO'],
                        headerOrder: ExportHeaderOrder.Default,
                        filter: defaultProps.filter,
                        ovOnly: false
                    }));
                    expect(defaultProps.onLoadingChange).toHaveBeenCalledWith(false);
                    expect(defaultProps.onClose).toHaveBeenCalled();
                    expect(showSnackbarMessage).toHaveBeenCalledWith({
                        message: "Your export job is underway. We'll send an email with the download link once it's complete.",
                        action: {
                            label: 'View progress',
                            onClick: expect.any(Function)
                        }
                    });
                    return [2 /*return*/];
            }
        });
    }); });
    it('should pass ovOnly true to all export jobs when Export OV Only is checked', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp().user;
                    return [4 /*yield*/, user.click(screen.getByRole('checkbox', { name: 'Export Operational Values (OV) only' }))];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getByRole('button', { name: 'Export' }))];
                case 2:
                    _a.sent();
                    expect(exportData).toHaveBeenCalledTimes(2);
                    expect(exportData).toHaveBeenCalledWith(expect.objectContaining({ ovOnly: true }));
                    expect(exportData).toHaveBeenNthCalledWith(1, expect.objectContaining({
                        includeType: ['configuration/entityTypes/HCP'],
                        ovOnly: true
                    }));
                    expect(exportData).toHaveBeenNthCalledWith(2, expect.objectContaining({
                        includeType: ['configuration/entityTypes/HCO'],
                        ovOnly: true
                    }));
                    return [2 /*return*/];
            }
        });
    }); });
    it('should show error message when some export jobs failed', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user, errorMessage;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    exportData.mockRejectedValueOnce(new Error('Failed to export configuration/entityTypes/HCP'));
                    exportData.mockResolvedValueOnce({ status: 'scheduled' });
                    user = setUp().user;
                    return [4 /*yield*/, user.click(screen.getByRole('button', { name: 'Export' }))];
                case 1:
                    _a.sent();
                    expect(defaultProps.onLoadingChange).toHaveBeenCalledWith(true);
                    expect(exportData).toHaveBeenCalledTimes(2);
                    expect(defaultProps.onLoadingChange).toHaveBeenCalledWith(false);
                    expect(defaultProps.onClose).toHaveBeenCalled();
                    return [4 /*yield*/, screen.findByTestId('error-message')];
                case 2:
                    errorMessage = _a.sent();
                    expect(errorMessage).toHaveTextContent('Failed to export configuration/entityTypes/HCP.');
                    return [2 /*return*/];
            }
        });
    }); });
});
