/**
 * Service responsible for creating portal users and ID mappings during signup
 */
import { Injectable, Inject, BadRequestException } from "@nestjs/common";
import { Logger } from "nestjs-pino";
import { PrismaService } from "@bff/infra/database/prisma.service.js";
import { extractErrorMessage } from "@bff/core/utils/error.util.js";
import { SignupWhmcsService } from "./signup-whmcs.service.js";

export interface UserCreationParams {
  email: string;
  passwordHash: string;
  whmcsClientId: number;
  sfAccountId: string;
}

export interface CreatedUserResult {
  userId: string;
}

@Injectable()
export class SignupUserCreationService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly whmcsService: SignupWhmcsService,
    @Inject(Logger) private readonly logger: Logger
  ) {}

  /**
   * Create user and ID mapping in a single transaction
   * Compensates by marking WHMCS client for cleanup on failure
   */
  async createUserWithMapping(params: UserCreationParams): Promise<CreatedUserResult> {
    try {
      const result = await this.prisma.$transaction(async tx => {
        const created = await tx.user.create({
          data: {
            email: params.email,
            passwordHash: params.passwordHash,
            emailVerified: false,
            failedLoginAttempts: 0,
            lockedUntil: null,
            lastLoginAt: null,
          },
          select: { id: true, email: true },
        });

        await tx.idMapping.create({
          data: {
            userId: created.id,
            whmcsClientId: params.whmcsClientId,
            sfAccountId: params.sfAccountId,
          },
        });

        return { userId: created.id };
      });

      this.logger.debug("Created user with mapping", {
        userId: result.userId,
        email: params.email,
        whmcsClientId: params.whmcsClientId,
        sfAccountId: params.sfAccountId,
      });

      return result;
    } catch (dbError) {
      this.logger.error("Database transaction failed, cleaning up WHMCS client", {
        whmcsClientId: params.whmcsClientId,
        email: params.email,
        error: extractErrorMessage(dbError),
      });

      // Compensation: Mark the orphaned WHMCS client for cleanup
      await this.whmcsService.markClientForCleanup(params.whmcsClientId, params.email);

      throw new BadRequestException(
        `Failed to create user account: ${extractErrorMessage(dbError)}`
      );
    }
  }
}
