import { Injectable, Inject } from "@nestjs/common";
import { Logger } from "nestjs-pino";
import { SalesforceFacade } from "@bff/integrations/salesforce/facades/salesforce.facade.js";
import { extractErrorMessage } from "@bff/core/utils/error.util.js";
import {
  PORTAL_STATUS_ACTIVE,
  type PortalRegistrationSource,
} from "@bff/modules/auth/constants/portal.constants.js";

export interface UpdateSalesforceFlagsParams {
  sfAccountId: string;
  whmcsClientId?: number;
  source?: PortalRegistrationSource;
}

/**
 * Step: Update Salesforce portal status flags after account creation.
 *
 * Sets the account to "Active" and optionally updates the registration source
 * and WHMCS account link.
 *
 * No rollback — this is retry-safe and idempotent.
 */
@Injectable()
export class UpdateSalesforceFlagsStep {
  constructor(
    private readonly salesforceFacade: SalesforceFacade,
    @Inject(Logger) private readonly logger: Logger
  ) {}

  async execute(params: UpdateSalesforceFlagsParams): Promise<void> {
    const { sfAccountId, whmcsClientId, source } = params;

    try {
      await this.salesforceFacade.updateAccountPortalFields(sfAccountId, {
        status: PORTAL_STATUS_ACTIVE,
        ...(source && { source }),
        lastSignedInAt: new Date(),
        ...(whmcsClientId !== undefined && { whmcsAccountId: whmcsClientId }),
      });

      this.logger.log({ sfAccountId, source, whmcsClientId }, "Salesforce portal flags updated");
    } catch (error) {
      // Non-critical: log warning but do not throw.
      // The account is already created; SF flags can be fixed later.
      this.logger.warn(
        { sfAccountId, error: extractErrorMessage(error) },
        "Failed to update Salesforce portal flags"
      );
    }
  }
}
