import { Controller, Get, Query, Param } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConversationORM } from '../../infrastructure/database/postgres/entities/conversation.orm';
import { MessageORM } from '../../infrastructure/database/postgres/entities/message.orm';

/**
 * 内部 API - 供其他微服务调用
 * 不暴露给外部用户
 */
@Controller('internal/conversations')
export class InternalConversationController {
  constructor(
    @InjectRepository(ConversationORM)
    private conversationRepo: Repository<ConversationORM>,
    @InjectRepository(MessageORM)
    private messageRepo: Repository<MessageORM>,
  ) {}

  /**
   * 查询对话列表（供 evolution-service 使用）
   */
  @Get()
  async findConversations(
    @Query('status') status?: string,
    @Query('hoursBack') hoursBack?: string,
    @Query('minMessageCount') minMessageCount?: string,
    @Query('limit') limit?: string,
  ) {
    const queryBuilder = this.conversationRepo.createQueryBuilder('c');

    if (status) {
      queryBuilder.andWhere('c.status = :status', { status });
    }

    if (hoursBack) {
      const cutoffTime = new Date();
      cutoffTime.setHours(cutoffTime.getHours() - parseInt(hoursBack));
      queryBuilder.andWhere('c.created_at > :cutoffTime', { cutoffTime });
    }

    if (minMessageCount) {
      queryBuilder.andWhere('c.message_count > :minCount', {
        minCount: parseInt(minMessageCount),
      });
    }

    queryBuilder.orderBy('c.created_at', 'DESC');

    if (limit) {
      queryBuilder.take(parseInt(limit));
    }

    const conversations = await queryBuilder.getMany();

    return {
      success: true,
      data: conversations,
    };
  }

  /**
   * 获取对话的消息（供 evolution-service 使用）
   */
  @Get(':id/messages')
  async getMessages(@Param('id') conversationId: string) {
    const messages = await this.messageRepo.find({
      where: { conversationId },
      order: { createdAt: 'ASC' },
    });

    return {
      success: true,
      data: messages,
    };
  }

  /**
   * 统计对话数量（供 evolution-service 使用）
   */
  @Get('count')
  async countConversations(
    @Query('status') status?: string,
    @Query('daysBack') daysBack?: string,
  ) {
    const queryBuilder = this.conversationRepo.createQueryBuilder('c');

    if (status) {
      queryBuilder.andWhere('c.status = :status', { status });
    }

    if (daysBack) {
      const cutoffTime = new Date();
      cutoffTime.setDate(cutoffTime.getDate() - parseInt(daysBack));
      queryBuilder.andWhere('c.updated_at > :cutoffTime', { cutoffTime });
    }

    const count = await queryBuilder.getCount();

    return {
      success: true,
      data: { count },
    };
  }
}
