import { Injectable } from "@nestjs/common";
import { type AgentConversationMessage, type Prisma } from "@prisma/client";
import { PrismaService } from "../../prisma/prisma.service";

@Injectable()
export class AgentMessagesService {
  constructor(private readonly prisma: PrismaService) {}

  async getMessages(
    sessionId: string,
    limit: number,
    skip: number
  ): Promise<{
    messages: AgentConversationMessage[];
    total: number;
  }> {
    const where = { sessionId };

    const [messages, total] = await Promise.all([
      this.prisma.agentConversationMessage.findMany({
        where,
        orderBy: {
          timestamp: "desc",
        },
        take: limit,
        skip,
      }),
      this.prisma.agentConversationMessage.count({ where }),
    ]);

    return {
      messages,
      total,
    };
  }

  async getReplayMessages(sessionId: string, limit = 50): Promise<AgentConversationMessage[]> {
    const messages = await this.prisma.agentConversationMessage.findMany({
      where: { sessionId },
      orderBy: {
        timestamp: "desc",
      },
      take: limit,
    });

    return messages.reverse();
  }

  async getMessagesAfter(
    sessionId: string,
    lastSeenTimestamp: Date,
    lastSeenMessageId: string | null
  ): Promise<AgentConversationMessage[]> {
    const where: Prisma.AgentConversationMessageWhereInput = {
      sessionId,
      ...(lastSeenMessageId
        ? {
            OR: [
              {
                timestamp: {
                  gt: lastSeenTimestamp,
                },
              },
              {
                timestamp: lastSeenTimestamp,
                id: {
                  gt: lastSeenMessageId,
                },
              },
            ],
          }
        : {
            timestamp: {
              gt: lastSeenTimestamp,
            },
          }),
    };

    return this.prisma.agentConversationMessage.findMany({
      where,
      orderBy: [{ timestamp: "asc" }, { id: "asc" }],
    });
  }
}
