import Add from '../../../../../node_modules/@mui/icons-material/esm/Add.mjs';
import React__default, { useState } from 'react';
import '../../../../../_virtual/index2.mjs';
import { useSWRConfig } from '../../../../../node_modules/swr/_internal/dist/index.mjs';
import { Button } from '../components/Button.mjs';
import { Checkbox } from '../components/Checkbox.mjs';
import { FlexBox } from '../shared/components/FlexBox.mjs';
import { Modal } from '../components/Modal.mjs';
import { SCIMFields } from '../components/ScimFields.mjs';
import { Table } from '../components/Table.mjs';
import { Typography } from '../components/Typography.mjs';
import { NO_VALUE } from '../utils/noValue.mjs';
import { prependAsterisks } from '../utils/prependAsterisks.mjs';
import { useMutateWithToast } from '../utils/useMutateWithToast.mjs';
import { useRbac } from '../utils/useRbac.mjs';
import { scimGetConnectionKey } from '../utils/useScimConnection.mjs';
import { useStytchClient } from '../utils/useStytchClient.mjs';
import { getFieldBy, DEFAULT_HEADER_BEARER_TOKEN_LABEL } from './scimInfo.mjs';
import { useModalState } from '../shared/components/Modal.mjs';

const tokenRotationItemRenderers = ({ isCurrent, tokenTitle, tokenLastFour, tokenExpiresAt })=>[
        {
            title: `${isCurrent ? 'Current' : 'Next'} ${tokenTitle}`,
            getValue: ()=>{
                return /*#__PURE__*/ React__default.createElement(Typography, {
                    variant: "body2"
                }, tokenLastFour ? prependAsterisks(tokenLastFour) : NO_VALUE);
            },
            width: 300
        },
        {
            title: 'Expires',
            getValue: ()=>{
                return /*#__PURE__*/ React__default.createElement(Typography, {
                    variant: "body2"
                }, tokenExpiresAt ? new Date(tokenExpiresAt).toLocaleString() : NO_VALUE);
            }
        }
    ];
const tokenRotationKeyExtractor = (item)=>item.connection_id;
const useMutateCancelTokenRotation = ()=>{
    const client = useStytchClient();
    const { mutate: mutateSWR } = useSWRConfig();
    return useMutateWithToast(async (connectionId)=>{
        return await mutateSWR(scimGetConnectionKey(connectionId), async ()=>{
            const result = await client.scim.rotateCancel(connectionId);
            return result.connection;
        }, {
            populateCache: true,
            revalidate: false
        });
    });
};
const ManageTokenRotation = ({ connection })=>{
    const client = useStytchClient();
    const { mutate: mutateSWR } = useSWRConfig();
    const [isCancelAction, setIsCancelAction] = useState();
    const bearerTokenField = getFieldBy({
        idp: connection.identity_provider,
        key: 'bearer_token'
    });
    const bearerTokenFieldLabel = bearerTokenField?.label ?? DEFAULT_HEADER_BEARER_TOKEN_LABEL;
    const { mutate: cancelTokenRotation } = useMutateCancelTokenRotation();
    const { mutate: completeTokenRotation } = useMutateWithToast(async (connectionId)=>{
        return await mutateSWR(scimGetConnectionKey(connectionId), async ()=>{
            const result = await client.scim.rotateComplete(connectionId);
            return result.connection;
        }, {
            populateCache: true,
            revalidate: false
        });
    });
    const tokenRotationModalProps = useModalState(async ()=>{
        const connectionId = connection.connection_id;
        if (isCancelAction) {
            await cancelTokenRotation(connectionId);
        } else {
            await completeTokenRotation(connectionId);
        }
        return tokenRotationModalProps.close();
    });
    const { bearer_token_last_four: currentTokenLastFour, next_bearer_token_last_four: nextTokenLastFour, next_bearer_token_expires_at: nextTokenExpiresAt } = connection;
    const nextTokenItemRenderers = tokenRotationItemRenderers({
        isCurrent: false,
        tokenTitle: bearerTokenFieldLabel,
        tokenLastFour: nextTokenLastFour,
        tokenExpiresAt: nextTokenExpiresAt
    });
    const handleActionRotation = ({ isCancel })=>{
        setIsCancelAction(isCancel);
        tokenRotationModalProps.open();
    };
    const warningText = isCancelAction ? `The token ${prependAsterisks(nextTokenLastFour)} will be deactivated and no longer usable.` : `The token ${prependAsterisks(currentTokenLastFour)} will be deactivated and no longer usable. It will be replaced with the token ${prependAsterisks(nextTokenLastFour)}.`;
    const confirmationText = isCancelAction ? 'Confirm that you are not using this token before continuing.' : `Make sure you are only using the token ${prependAsterisks(nextTokenLastFour)} before completing rotation.`;
    return /*#__PURE__*/ React__default.createElement(React__default.Fragment, null, /*#__PURE__*/ React__default.createElement(Table, {
        titleVariant: "caption",
        itemRenderer: nextTokenItemRenderers,
        items: [
            connection
        ],
        rowKeyExtractor: tokenRotationKeyExtractor,
        disableBottomBorder: true
    }), /*#__PURE__*/ React__default.createElement(Modal, {
        ...tokenRotationModalProps,
        title: `${isCancelAction ? 'Cancel' : 'Complete'} token rotation?`,
        confirmButtonText: `${isCancelAction ? 'Cancel' : 'Complete'} rotation`,
        warning: true
    }, /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "column",
        gap: 2
    }, /*#__PURE__*/ React__default.createElement(Typography, null, warningText), /*#__PURE__*/ React__default.createElement(Typography, null, confirmationText))), /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "row",
        gap: 2
    }, /*#__PURE__*/ React__default.createElement(Button, {
        compact: true,
        variant: "ghost",
        onClick: ()=>handleActionRotation({
                isCancel: true
            }),
        warning: true
    }, "Cancel rotation"), /*#__PURE__*/ React__default.createElement(Button, {
        compact: true,
        variant: "ghost",
        onClick: ()=>handleActionRotation({
                isCancel: false
            })
    }, "Complete rotation")));
};
const StartTokenRotation = ({ connection, handleRotation })=>{
    const client = useStytchClient();
    const { mutate: mutateSWR } = useSWRConfig();
    const { mutate: startTokenRotation } = useMutateWithToast(async (connectionId)=>{
        return await mutateSWR(scimGetConnectionKey(connectionId), async ()=>{
            const result = await client.scim.rotateStart(connectionId);
            return {
                ...result.connection,
                next_bearer_token_last_four: result.connection.next_bearer_token.slice(-4)
            };
        }, {
            populateCache: true,
            revalidate: false
        });
    });
    const handleActionClick = ()=>{
        startTokenRotation(connection.connection_id).then((result)=>{
            handleRotation(result);
        });
    };
    return /*#__PURE__*/ React__default.createElement(React__default.Fragment, null, /*#__PURE__*/ React__default.createElement(Button, {
        compact: true,
        variant: "ghost",
        startIcon: /*#__PURE__*/ React__default.createElement(Add, null),
        onClick: handleActionClick
    }, "Start token rotation"));
};
const TokenRotationSection = ({ connection })=>{
    const { data: canUpdateScim } = useRbac('stytch.scim', 'update');
    const canRotateToken = canUpdateScim ?? false;
    const { mutate: cancelTokenRotation } = useMutateCancelTokenRotation();
    const canStartTokenRotation = !connection.next_bearer_token_last_four;
    const bearerTokenField = getFieldBy({
        idp: connection.identity_provider,
        key: 'bearer_token'
    });
    const bearerTokenFieldLabel = bearerTokenField?.label ?? DEFAULT_HEADER_BEARER_TOKEN_LABEL;
    const currentTokenItemRenderers = tokenRotationItemRenderers({
        isCurrent: true,
        tokenTitle: bearerTokenFieldLabel,
        tokenLastFour: connection.bearer_token_last_four,
        tokenExpiresAt: connection.bearer_token_expires_at
    });
    const [hasUserConfirmedCopy, setHasUserConfirmedCopy] = useState(false);
    const [connectionWithNextToken, setConnectionWithNextToken] = useState();
    const nextTokenField = {
        label: `Click to copy your new ${bearerTokenFieldLabel}`,
        scimConnectionKey: 'next_bearer_token',
        isCopyable: true
    };
    const handleRotation = (connection)=>{
        setConnectionWithNextToken(connection);
        open();
    };
    const handleClose = ()=>{
        cancelTokenRotation(connection.connection_id);
        close();
    };
    const { open, close, ...props } = useModalState(async ()=>{
        setHasUserConfirmedCopy(false);
        return close();
    });
    return /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "column",
        gap: 2
    }, /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "body2"
    }, "For security reasons, you may only view the last 4 digits of the token. If you have lost your token, create a replacement by starting a token rotation."), /*#__PURE__*/ React__default.createElement(Table, {
        titleVariant: "caption",
        itemRenderer: currentTokenItemRenderers,
        items: [
            connection
        ],
        rowKeyExtractor: tokenRotationKeyExtractor,
        disableBottomBorder: true
    }), /*#__PURE__*/ React__default.createElement(Modal, {
        ...props,
        title: "Start HTTP Header Bearer Token Rotation",
        confirmButtonText: "Done",
        disableConfirm: !hasUserConfirmedCopy,
        close: handleClose,
        keepOpenOnConfirm: true
    }, /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "column",
        gap: 2
    }, /*#__PURE__*/ React__default.createElement(Typography, null, "You will not be able to see the full token again. Make sure to copy your token to your IdP."), connectionWithNextToken && /*#__PURE__*/ React__default.createElement(SCIMFields, {
        fields: [
            nextTokenField
        ],
        connection: connectionWithNextToken
    }), /*#__PURE__*/ React__default.createElement(Checkbox, {
        label: "I have copied the token to my IdP.",
        checked: hasUserConfirmedCopy,
        onClick: (value)=>setHasUserConfirmedCopy(value)
    }))), canRotateToken && (canStartTokenRotation ? /*#__PURE__*/ React__default.createElement(StartTokenRotation, {
        connection: connection,
        handleRotation: handleRotation
    }) : /*#__PURE__*/ React__default.createElement(ManageTokenRotation, {
        connection: connection
    })));
};

export { TokenRotationSection };
//# sourceMappingURL=SCIMConnectionTokenRotationSection.mjs.map
