// DBIS IRU TypeScript/JavaScript SDK
// Client library for IRU integration

export interface IRUClientConfig {
  apiBaseUrl: string;
  apiKey?: string;
  timeout?: number;
}

export interface IRUOffering {
  id: string;
  offeringId: string;
  name: string;
  description?: string;
  capacityTier: number;
  institutionalType: string;
  basePrice?: number;
  currency: string;
}

export interface IRUInquiry {
  offeringId: string;
  organizationName: string;
  institutionalType: string;
  jurisdiction: string;
  contactEmail: string;
  contactPhone?: string;
  contactName: string;
  estimatedVolume?: string;
  expectedGoLive?: Date;
}

export interface IRUSubscription {
  subscriptionId: string;
  offeringId: string;
  subscriptionStatus: string;
  activationDate?: Date;
}

/** Public GET /inquiries/:id (no organization, contact, qualification, risk, or notes) */
export interface IRUPublicInquiryStatus {
  inquiryId: string;
  status: string;
  offering: { name: string; capacityTier: number };
  submittedAt: string;
  acknowledgedAt: string | null;
  reviewedAt: string | null;
  completedAt: string | null;
}

export class IRUClient {
  private config: IRUClientConfig;
  private baseUrl: string;

  constructor(config: IRUClientConfig) {
    this.config = {
      timeout: 30000,
      ...config,
    };
    this.baseUrl = config.apiBaseUrl.replace(/\/$/, '');
  }

  /**
   * Get all IRU offerings
   */
  async getOfferings(filters?: {
    capacityTier?: number;
    institutionalType?: string;
  }): Promise<IRUOffering[]> {
    const params = new URLSearchParams();
    if (filters?.capacityTier) {
      params.append('capacityTier', filters.capacityTier.toString());
    }
    if (filters?.institutionalType) {
      params.append('institutionalType', filters.institutionalType);
    }

    const response = await this.request<{ success: boolean; data: IRUOffering[] }>(
      `/api/v1/iru/marketplace/offerings${params.toString() ? `?${params.toString()}` : ''}`
    );

    return response.data;
  }

  /**
   * Get offering by ID
   */
  async getOffering(offeringId: string): Promise<IRUOffering> {
    const response = await this.request<{ success: boolean; data: IRUOffering }>(
      `/api/v1/iru/marketplace/offerings/${offeringId}`
    );

    return response.data;
  }

  /**
   * Submit inquiry
   */
  async submitInquiry(inquiry: IRUInquiry): Promise<{ inquiryId: string; status: string; message: string }> {
    const response = await this.request<{ success: boolean; data: { inquiryId: string; status: string; message: string } }>(
      '/api/v1/iru/marketplace/inquiries',
      {
        method: 'POST',
        body: JSON.stringify(inquiry),
      }
    );

    return response.data;
  }

  /**
   * Get public inquiry status (workflow + offering summary only).
   */
  async getInquiryStatus(inquiryId: string): Promise<IRUPublicInquiryStatus> {
    const response = await this.request<{ success: boolean; data: IRUPublicInquiryStatus }>(
      `/api/v1/iru/marketplace/inquiries/${inquiryId}`
    );

    return response.data;
  }

  /**
   * Calculate pricing
   */
  async calculatePricing(offeringId: string, usageProfile?: any): Promise<any> {
    const params = usageProfile ? `?usageProfile=${encodeURIComponent(JSON.stringify(usageProfile))}` : '';
    const response = await this.request<{ success: boolean; data: any }>(
      `/api/v1/iru/marketplace/offerings/${offeringId}/pricing${params}`
    );

    return response.data;
  }

  /**
   * Get dashboard
   */
  async getDashboard(): Promise<any> {
    const response = await this.request<{ success: boolean; data: any }>(
      '/api/v1/iru/portal/dashboard'
    );

    return response.data;
  }

  /**
   * Get service health
   */
  async getServiceHealth(subscriptionId: string): Promise<any> {
    const response = await this.request<{ success: boolean; data: any }>(
      `/api/v1/iru/portal/monitoring/${subscriptionId}/health`
    );

    return response.data;
  }

  /**
   * Get deployment status
   */
  async getDeploymentStatus(subscriptionId: string): Promise<any> {
    const response = await this.request<{ success: boolean; data: any }>(
      `/api/v1/iru/portal/deployment/${subscriptionId}`
    );

    return response.data;
  }

  /**
   * Make HTTP request
   */
  private async request<T>(path: string, options: RequestInit = {}): Promise<T> {
    const url = `${this.baseUrl}${path}`;
    const headers: HeadersInit = {
      'Content-Type': 'application/json',
      ...options.headers,
    };

    if (this.config.apiKey) {
      headers['Authorization'] = `Bearer ${this.config.apiKey}`;
    }

    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);

    try {
      const response = await fetch(url, {
        ...options,
        headers,
        signal: controller.signal,
      });

      clearTimeout(timeoutId);

      if (!response.ok) {
        const error = await response.json().catch(() => ({ message: response.statusText }));
        throw new Error(error.message || `HTTP ${response.status}`);
      }

      return await response.json();
    } catch (error) {
      clearTimeout(timeoutId);
      if (error instanceof Error && error.name === 'AbortError') {
        throw new Error('Request timeout');
      }
      throw error;
    }
  }
}

// Export convenience function
export function createIRUClient(config: IRUClientConfig): IRUClient {
  return new IRUClient(config);
}

// Default export
export default IRUClient;
