import { k as useState, f as useEffect } from './dom-context-hooks.module-50442785.js';
import { d as dist, J, X as Xe, $ as $e } from './index.module-b23fdad8.js';

const UserLookupQuery = dist.gql `
  query userLookup {
    viewer {
      ... on User {
        id
        accountId
        email
        impactConnection {
          user {
            id
            email
          }
        }
      }
    }
  }
`;
const ParticipantVerificationEmailMutation = dist.gql `
  mutation requestUserEmailVerification($user: UserIdInput!) {
    requestUserEmailVerification(user: $user) {
      success
    }
  }
`;
const ImpactVerificationEmailMutation = dist.gql `
  mutation requestImpactPublisherEmail2FA($user: UserIdInput!) {
    requestImpactPublisherEmail2FA(user: $user) {
      success
    }
  }
`;
const VerifyUserEmailMutation = dist.gql `
  mutation verifyUserEmail($user: UserIdInput!, $code: String!) {
    verifyUserEmail(user: $user, code: $code) {
      id
      accountId
      email
      emailVerified
    }
  }
`;
const SubmitImpactCodeMutation = dist.gql `
  mutation submitImpactPublisherEmail2FACode(
    $user: UserIdInput!
    $code: String!
  ) {
    submitImpactPublisherEmail2FACode(user: $user, code: $code) {
      verifiedEmail
      accessKey
    }
  }
`;
// ! It's important when using this hook to ensure initialisation
// ! is done before calling any mutations
function useVerificationEmail() {
  const userIdentity = J();
  const [verificationEmail, setVerificationEmail] = useState(null);
  const [hasEmails, setHasEmails] = useState({
    participant: false,
    impact: false,
  });
  const [fetch] = Xe(UserLookupQuery);
  // Send mutations
  const [sendParticipantEmail, { loading: participantEmailLoading, errors: participantEmailErrors },] = $e(ParticipantVerificationEmailMutation);
  const [sendImpactEmail, { loading: impactEmailLoading, errors: impactEmailErrors },] = $e(ImpactVerificationEmailMutation);
  const sendLoading = participantEmailLoading || impactEmailLoading;
  const sendErrors = participantEmailErrors || impactEmailErrors;
  // Verification mutations
  const [verifyUserEmail, { loading: verifyMutationLoading, errors: verifyMutationErrors },] = $e(VerifyUserEmailMutation);
  const [submitImpactCode, { loading: submitImpactCodeLoading, errors: submitImpactCodeErrors },] = $e(SubmitImpactCodeMutation);
  const verifyLoading = verifyMutationLoading || submitImpactCodeLoading;
  const verifyErrors = verifyMutationErrors || submitImpactCodeErrors;
  const [initialized, setInitialized] = useState(false);
  const initialise = async () => {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    try {
      const lookup = await fetch({});
      if (!lookup || lookup instanceof Error)
        throw new Error();
      setHasEmails({
        participant: !!((_a = lookup === null || lookup === void 0 ? void 0 : lookup.viewer) === null || _a === void 0 ? void 0 : _a.email),
        impact: !!((_d = (_c = (_b = lookup === null || lookup === void 0 ? void 0 : lookup.viewer) === null || _b === void 0 ? void 0 : _b.impactConnection) === null || _c === void 0 ? void 0 : _c.user) === null || _d === void 0 ? void 0 : _d.email),
      });
      setVerificationEmail(((_g = (_f = (_e = lookup === null || lookup === void 0 ? void 0 : lookup.viewer) === null || _e === void 0 ? void 0 : _e.impactConnection) === null || _f === void 0 ? void 0 : _f.user) === null || _g === void 0 ? void 0 : _g.email) || ((_h = lookup === null || lookup === void 0 ? void 0 : lookup.viewer) === null || _h === void 0 ? void 0 : _h.email) ||
        null);
      setInitialized(true);
    }
    catch (e) {
      console.error("Could not initialise verification", e);
    }
  };
  const sendVerificationEmail = async () => {
    let result = null;
    if (!initialized)
      return result;
    if (!hasEmails.participant && !hasEmails.impact)
      return result;
    try {
      const request = hasEmails.impact ? sendImpactEmail : sendParticipantEmail;
      const res = await request({
        user: {
          id: userIdentity.id,
          accountId: userIdentity.accountId,
        },
      });
      if (res instanceof Error || !res)
        throw new Error();
      result = hasEmails.impact
        ? res.requestImpactPublisherEmail2FA
        : res.requestUserEmailVerification;
    }
    catch (e) {
      console.error("Could not send verification email", e);
    }
    finally {
      return result;
    }
  };
  const verifyVerificationEmail = async (code) => {
    var _a;
    let result = null;
    if (!initialized)
      return result;
    if (!hasEmails.participant && !hasEmails.impact)
      return result;
    try {
      const request = hasEmails.impact ? submitImpactCode : verifyUserEmail;
      const res = await request({
        user: {
          id: userIdentity.id,
          accountId: userIdentity.accountId,
        },
        code,
      });
      if (res instanceof Error || !res)
        throw new Error();
      result = {
        success: true,
        accessKey: hasEmails.impact
          ? (_a = res.submitImpactPublisherEmail2FACode) === null || _a === void 0 ? void 0 : _a.accessKey : undefined,
      };
    }
    catch (e) {
      console.error("Could not verify email", e);
    }
    finally {
      return result;
    }
  };
  useEffect(() => {
    if (!initialized)
      initialise();
  }, []);
  return {
    initialized,
    verificationEmail,
    send: [
      sendVerificationEmail,
      { loading: sendLoading, errors: sendErrors },
    ],
    verify: [
      verifyVerificationEmail,
      { loading: verifyLoading, errors: verifyErrors },
    ],
  };
}

export { useVerificationEmail as u };
