import { AlertSource, AlertCategory, Severity, EntityType, NormalizedAlertInput } from "@shieldai/types";

export interface BrokerAlertInput {
  userId: string;
  brokerName: string;
  brokerId: string;
  category: AlertCategory;
  severity: Severity;
  title: string;
  description: string;
  entities: Array<{ type: EntityType; value: string }>;
  metadata?: Record<string, unknown>;
}

export class BrokerAlertPipeline {
  async sendListingFoundAlert(input: BrokerAlertInput) {
    const alert = {
      source: AlertSource.INFO_BROKER,
      category: AlertCategory.INFO_BROKER_LISTING,
      severity: input.severity,
      userId: input.userId,
      title: input.title,
      description: input.description,
      entities: input.entities,
      sourceAlertId: `broker_listing_${input.brokerId}_${Date.now()}`,
      payload: {
        brokerId: input.brokerId,
        brokerName: input.brokerName,
        ...input.metadata,
      },
      timestamp: new Date(),
    };

    return this.normalizeAndSend(alert);
  }

  async sendRemovalStatusAlert(input: BrokerAlertInput) {
    const alert = {
      source: AlertSource.INFO_BROKER,
      category: AlertCategory.INFO_BROKER_REMOVAL,
      severity: input.severity,
      userId: input.userId,
      title: input.title,
      description: input.description,
      entities: input.entities,
      sourceAlertId: `broker_removal_${input.brokerId}_${Date.now()}`,
      payload: {
        brokerId: input.brokerId,
        brokerName: input.brokerName,
        ...input.metadata,
      },
      timestamp: new Date(),
    };

    return this.normalizeAndSend(alert);
  }

  private async normalizeAndSend(alert: NormalizedAlertInput) {
    try {
      const { correlationService } = await import("@shieldai/correlation");
      return correlationService.ingestGenericAlert(alert);
    } catch {
      console.error("[BrokerAlert] Failed to send alert:", alert.sourceAlertId);
      return alert;
    }
  }
}

export const brokerAlertPipeline = new BrokerAlertPipeline();
