import { Injectable, Logger } from '@nestjs/common';
import {
  IAiServiceClient,
  IssuerReviewRequest,
  IssuerReviewResult,
} from '../../domain/ports/ai-service.client.interface';

@Injectable()
export class AiServiceClient implements IAiServiceClient {
  private readonly logger = new Logger('AiServiceClient');
  private readonly aiServiceUrl: string;

  constructor() {
    this.aiServiceUrl = process.env.AI_SERVICE_URL || 'http://localhost:3006';
  }

  /**
   * Call external AI service for issuer pre-review.
   * Returns null if the service is unavailable (caller handles fallback).
   */
  async reviewIssuers(issuers: IssuerReviewRequest[]): Promise<IssuerReviewResult[] | null> {
    try {
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 15000);

      const response = await fetch(`${this.aiServiceUrl}/api/v1/admin/issuer-review`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          issuers: issuers.map((i) => ({
            id: i.id,
            companyName: i.companyName,
            businessLicense: i.businessLicense,
            contactName: i.contactName,
            contactPhone: i.contactPhone,
            contactEmail: i.contactEmail,
            description: i.description,
            creditScore: i.creditScore,
            createdAt: i.createdAt,
          })),
        }),
        signal: controller.signal,
      });

      clearTimeout(timeoutId);

      if (response.ok) {
        const aiResults = (await response.json()) as {
          reviews: IssuerReviewResult[];
        };
        return aiResults.reviews || null;
      }

      this.logger.warn(`AI service returned status ${response.status}`);
      return null;
    } catch (error) {
      this.logger.warn(`AI service unavailable: ${error.message}`);
      return null;
    }
  }
}
