import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AiConversation } from '../../domain/entities/ai-conversation.entity';
import { IConversationRepository } from '../../domain/repositories/conversation.repository.interface';

@Injectable()
export class ConversationRepository implements IConversationRepository {
  constructor(
    @InjectRepository(AiConversation)
    private readonly repo: Repository<AiConversation>,
  ) {}

  async findById(id: string): Promise<AiConversation | null> {
    return this.repo.findOne({ where: { id } });
  }

  async findBySessionId(sessionId: string): Promise<AiConversation | null> {
    return this.repo.findOne({ where: { sessionId } });
  }

  async findByUserId(userId: string, skip: number, take: number): Promise<[AiConversation[], number]> {
    return this.repo.findAndCount({
      where: { userId },
      skip,
      take,
      order: { updatedAt: 'DESC' },
    });
  }

  async save(conversation: AiConversation): Promise<AiConversation> {
    return this.repo.save(conversation);
  }

  async countByUserId(userId: string): Promise<number> {
    return this.repo.count({ where: { userId } });
  }
}
