import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

/**
 * 对话数据传输对象
 */
export interface ConversationDto {
  id: string;
  userId: string;
  status: string;
  title: string;
  summary: string;
  category: string;
  messageCount: number;
  rating: number;
  hasConverted: boolean;
  createdAt: Date;
  updatedAt: Date;
}

/**
 * 消息数据传输对象
 */
export interface MessageDto {
  id: string;
  conversationId: string;
  role: 'user' | 'assistant' | 'system';
  content: string;
  createdAt: Date;
}

/**
 * API 响应类型
 */
interface ApiResponse<T> {
  success: boolean;
  data: T;
}

/**
 * Conversation Service 客户端
 * 用于调用 conversation-service 的内部 API
 */
@Injectable()
export class ConversationClient {
  private readonly baseUrl: string;

  constructor(private configService: ConfigService) {
    this.baseUrl = this.configService.get<string>(
      'CONVERSATION_SERVICE_URL',
      'http://conversation-service:3004',
    );
  }

  /**
   * 查询对话列表
   */
  async findConversations(options: {
    status?: string;
    hoursBack?: number;
    minMessageCount?: number;
    limit?: number;
  }): Promise<ConversationDto[]> {
    const params = new URLSearchParams();

    if (options.status) params.append('status', options.status);
    if (options.hoursBack) params.append('hoursBack', options.hoursBack.toString());
    if (options.minMessageCount) params.append('minMessageCount', options.minMessageCount.toString());
    if (options.limit) params.append('limit', options.limit.toString());

    const url = `${this.baseUrl}/api/internal/conversations?${params.toString()}`;

    try {
      const response = await fetch(url);
      const data = (await response.json()) as ApiResponse<ConversationDto[]>;

      if (!data.success) {
        throw new Error('Failed to fetch conversations');
      }

      return data.data;
    } catch (error) {
      console.error('[ConversationClient] Error fetching conversations:', error);
      throw error;
    }
  }

  /**
   * 获取对话的消息
   */
  async getMessages(conversationId: string): Promise<MessageDto[]> {
    const url = `${this.baseUrl}/api/internal/conversations/${conversationId}/messages`;

    try {
      const response = await fetch(url);
      const data = (await response.json()) as ApiResponse<MessageDto[]>;

      if (!data.success) {
        throw new Error('Failed to fetch messages');
      }

      return data.data;
    } catch (error) {
      console.error('[ConversationClient] Error fetching messages:', error);
      throw error;
    }
  }

  /**
   * 统计对话数量
   */
  async countConversations(options: {
    status?: string;
    daysBack?: number;
  }): Promise<number> {
    const params = new URLSearchParams();

    if (options.status) params.append('status', options.status);
    if (options.daysBack) params.append('daysBack', options.daysBack.toString());

    const url = `${this.baseUrl}/api/internal/conversations/count?${params.toString()}`;

    try {
      const response = await fetch(url);
      const data = (await response.json()) as ApiResponse<{ count: number }>;

      if (!data.success) {
        throw new Error('Failed to count conversations');
      }

      return data.data.count;
    } catch (error) {
      console.error('[ConversationClient] Error counting conversations:', error);
      throw error;
    }
  }
}
