/**
 * Clean Alert Service - Matches Backend API Exactly
 *
 * Backend API: /services/alert_processor/app/api/alerts_clean.py
 *
 * NO backward compatibility, uses new type system from /api/types/events.ts
 */

import { apiClient } from '../client';
import type {
  EventResponse,
  Alert,
  Notification,
  Recommendation,
  PaginatedResponse,
  EventsSummary,
  EventQueryParams,
} from '../types/events';

const BASE_PATH = '/tenants';

// ============================================================
// QUERY METHODS
// ============================================================

/**
 * Get events list with filtering and pagination
 */
export async function getEvents(
  tenantId: string,
  params?: EventQueryParams
): Promise<PaginatedResponse<EventResponse>> {
  return await apiClient.get<PaginatedResponse<EventResponse>>(
    `${BASE_PATH}/${tenantId}/alerts`,
    { params }
  );
}

/**
 * Get single event by ID
 */
export async function getEvent(
  tenantId: string,
  eventId: string
): Promise<EventResponse> {
  return await apiClient.get<EventResponse>(
    `${BASE_PATH}/${tenantId}/alerts/${eventId}`
  );
}

/**
 * Get events summary for dashboard
 */
export async function getEventsSummary(
  tenantId: string
): Promise<EventsSummary> {
  return await apiClient.get<EventsSummary>(
    `${BASE_PATH}/${tenantId}/alerts/summary`
  );
}

// ============================================================
// MUTATION METHODS - Alerts
// ============================================================

export interface AcknowledgeAlertResponse {
  success: boolean;
  event_id: string;
  status: string;
}

/**
 * Acknowledge an alert
 */
export async function acknowledgeAlert(
  tenantId: string,
  alertId: string
): Promise<AcknowledgeAlertResponse> {
  return await apiClient.post<AcknowledgeAlertResponse>(
    `${BASE_PATH}/${tenantId}/alerts/${alertId}/acknowledge`
  );
}

export interface ResolveAlertResponse {
  success: boolean;
  event_id: string;
  status: string;
  resolved_at: string;
}

/**
 * Resolve an alert
 */
export async function resolveAlert(
  tenantId: string,
  alertId: string
): Promise<ResolveAlertResponse> {
  return await apiClient.post<ResolveAlertResponse>(
    `${BASE_PATH}/${tenantId}/alerts/${alertId}/resolve`
  );
}

export interface CancelAutoActionResponse {
  success: boolean;
  event_id: string;
  message: string;
  updated_type_class: string;
}

/**
 * Cancel an alert's auto-action (escalation countdown)
 */
export async function cancelAutoAction(
  tenantId: string,
  alertId: string
): Promise<CancelAutoActionResponse> {
  return await apiClient.post<CancelAutoActionResponse>(
    `${BASE_PATH}/${tenantId}/alerts/${alertId}/cancel-auto-action`
  );
}

// ============================================================
// MUTATION METHODS - Recommendations
// ============================================================

export interface DismissRecommendationResponse {
  success: boolean;
  event_id: string;
  dismissed_at: string;
}

/**
 * Dismiss a recommendation
 */
export async function dismissRecommendation(
  tenantId: string,
  recommendationId: string
): Promise<DismissRecommendationResponse> {
  return await apiClient.post<DismissRecommendationResponse>(
    `${BASE_PATH}/${tenantId}/recommendations/${recommendationId}/dismiss`
  );
}

// ============================================================
// INTERACTION TRACKING
// ============================================================

export interface RecordInteractionResponse {
  success: boolean;
  interaction_id: string;
  event_id: string;
  interaction_type: string;
}

/**
 * Record user interaction with an event (for analytics)
 */
export async function recordInteraction(
  tenantId: string,
  eventId: string,
  interactionType: string,
  metadata?: Record<string, any>
): Promise<RecordInteractionResponse> {
  return await apiClient.post<RecordInteractionResponse>(
    `${BASE_PATH}/${tenantId}/events/${eventId}/interactions`,
    {
      interaction_type: interactionType,
      interaction_metadata: metadata,
    }
  );
}

// ============================================================
// BULK OPERATIONS (by metadata)
// ============================================================

export interface BulkAcknowledgeResponse {
  success: boolean;
  acknowledged_count: number;
  alert_ids: string[];
}

/**
 * Acknowledge multiple alerts by metadata filter
 */
export async function acknowledgeAlertsByMetadata(
  tenantId: string,
  alertType: string,
  metadataFilter: Record<string, any>
): Promise<BulkAcknowledgeResponse> {
  return await apiClient.post<BulkAcknowledgeResponse>(
    `${BASE_PATH}/${tenantId}/alerts/bulk-acknowledge`,
    {
      alert_type: alertType,
      metadata_filter: metadataFilter,
    }
  );
}

export interface BulkResolveResponse {
  success: boolean;
  resolved_count: number;
  alert_ids: string[];
}

/**
 * Resolve multiple alerts by metadata filter
 */
export async function resolveAlertsByMetadata(
  tenantId: string,
  alertType: string,
  metadataFilter: Record<string, any>
): Promise<BulkResolveResponse> {
  return await apiClient.post<BulkResolveResponse>(
    `${BASE_PATH}/${tenantId}/alerts/bulk-resolve`,
    {
      alert_type: alertType,
      metadata_filter: metadataFilter,
    }
  );
}

// ============================================================
// EXPORT AS NAMED OBJECT
// ============================================================

export const alertService = {
  // Query
  getEvents,
  getEvent,
  getEventsSummary,

  // Alert mutations
  acknowledgeAlert,
  resolveAlert,
  cancelAutoAction,

  // Recommendation mutations
  dismissRecommendation,

  // Interaction tracking
  recordInteraction,

  // Bulk operations
  acknowledgeAlertsByMetadata,
  resolveAlertsByMetadata,
};

// ============================================================
// DEFAULT EXPORT
// ============================================================

export default alertService;
