/**
 * Get Started Machine — Actors
 *
 * Async API call actors invoked by XState states.
 * Each actor wraps an existing API function from the get-started API client.
 */

import { fromPromise } from "xstate";
import type { BilingualAddress } from "@customer-portal/domain/address";
import * as getStartedApi from "../api/get-started.api";
import type {
  SendCodeInput,
  SendCodeOutput,
  VerifyCodeInput,
  VerifyCodeOutput,
  CompleteAccountInput,
  CompleteAccountOutput,
  MigrateAccountInput,
  MigrateAccountOutput,
} from "./get-started.types";

/**
 * Send OTP verification code to email
 */
export const sendCodeActor = fromPromise<SendCodeOutput, SendCodeInput>(async ({ input }) => {
  return getStartedApi.sendVerificationCode({ email: input.email });
});

/**
 * Verify OTP code and get account status
 */
export const verifyCodeActor = fromPromise<VerifyCodeOutput, VerifyCodeInput>(async ({ input }) => {
  return getStartedApi.verifyCode({
    email: input.email,
    code: input.code,
    ...(input.handoffToken && { handoffToken: input.handoffToken }),
  });
});

/**
 * Complete account (new customer or SF-unmapped)
 */
export const completeAccountActor = fromPromise<CompleteAccountOutput, CompleteAccountInput>(
  async ({ input }) => {
    const { sessionToken, formData, accountStatus } = input;
    const isNewCustomer = accountStatus === "new_customer";

    return getStartedApi.completeAccount({
      sessionToken,
      password: formData.password,
      phone: formData.phone,
      dateOfBirth: formData.dateOfBirth,
      gender: formData.gender as "male" | "female" | "other",
      acceptTerms: formData.acceptTerms,
      marketingConsent: formData.marketingConsent,
      ...(isNewCustomer || formData.firstName ? { firstName: formData.firstName } : {}),
      ...(isNewCustomer || formData.lastName ? { lastName: formData.lastName } : {}),
      ...(formData.address?.postcode ? { address: formData.address as BilingualAddress } : {}),
    });
  }
);

/**
 * Migrate WHMCS account to portal
 */
export const migrateAccountActor = fromPromise<MigrateAccountOutput, MigrateAccountInput>(
  async ({ input }) => {
    return getStartedApi.migrateWhmcsAccount({
      sessionToken: input.sessionToken,
      password: input.password,
      acceptTerms: input.acceptTerms,
      marketingConsent: input.marketingConsent,
    });
  }
);
