/**
 * Service responsible for auth-related health checks
 */
import { Injectable, Inject } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Logger } from "nestjs-pino";
import { UsersService } from "@bff/modules/users/application/users.service.js";
import { WhmcsConnectionFacade } from "@bff/integrations/whmcs/facades/whmcs.facade.js";
import { SalesforceFacade } from "@bff/integrations/salesforce/facades/salesforce.facade.js";
import { extractErrorMessage } from "@bff/core/utils/error.util.js";

export interface AuthHealthCheckResult {
  status: "healthy" | "degraded";
  services: {
    database: boolean;
    whmcs: boolean;
    salesforce: boolean;
    whmcsConfig: {
      baseUrl: boolean;
      identifier: boolean;
      secret: boolean;
    };
    salesforceConfig: {
      connected: boolean;
    };
  };
  timestamp: string;
}

@Injectable()
export class AuthHealthService {
  constructor(
    private readonly usersService: UsersService,
    private readonly configService: ConfigService,
    private readonly whmcsConnectionService: WhmcsConnectionFacade,
    private readonly salesforceService: SalesforceFacade,
    @Inject(Logger) private readonly logger: Logger
  ) {}

  /**
   * Check health of all auth-related services
   */
  async check(): Promise<AuthHealthCheckResult> {
    const health = {
      database: false,
      whmcs: false,
      salesforce: false,
      whmcsConfig: {
        baseUrl: !!this.configService.get("WHMCS_BASE_URL"),
        identifier: !!this.configService.get("WHMCS_API_IDENTIFIER"),
        secret: !!this.configService.get("WHMCS_API_SECRET"),
      },
      salesforceConfig: {
        connected: false,
      },
    };

    // Check database
    try {
      await this.usersService.findByEmail("health-check@test.com");
      health.database = true;
    } catch (error) {
      this.logger.debug("Database health check failed", { error: extractErrorMessage(error) });
    }

    // Check WHMCS
    try {
      health.whmcs = await this.whmcsConnectionService.healthCheck();
    } catch (error) {
      this.logger.debug("WHMCS health check failed", { error: extractErrorMessage(error) });
    }

    // Check Salesforce
    try {
      health.salesforceConfig.connected = this.salesforceService.healthCheck();
      health.salesforce = health.salesforceConfig.connected;
    } catch (error) {
      this.logger.debug("Salesforce health check failed", { error: extractErrorMessage(error) });
    }

    return {
      status: health.database && health.whmcs && health.salesforce ? "healthy" : "degraded",
      services: health,
      timestamp: new Date().toISOString(),
    };
  }
}
