/**
 * Drizzle Log Chunk Repository Adapter
 *
 * Implements LogChunkRepository interface using Drizzle ORM.
 */

import { eq, asc, max } from 'drizzle-orm';
import { nanoid } from 'nanoid';
import type { DrizzleDatabase } from '../../index.js';
import { agentLogChunks } from '../../schema.js';
import type { LogChunkRepository } from '../log-chunk-repository.js';

export class DrizzleLogChunkRepository implements LogChunkRepository {
  constructor(private db: DrizzleDatabase) {}

  async insertChunk(data: {
    agentId: string;
    agentName: string;
    sessionNumber: number;
    content: string;
  }): Promise<void> {
    await this.db.insert(agentLogChunks).values({
      id: nanoid(),
      agentId: data.agentId,
      agentName: data.agentName,
      sessionNumber: data.sessionNumber,
      content: data.content,
      createdAt: new Date(),
    });
  }

  async findByAgentId(agentId: string): Promise<{ content: string; sessionNumber: number; createdAt: Date }[]> {
    return this.db
      .select({
        content: agentLogChunks.content,
        sessionNumber: agentLogChunks.sessionNumber,
        createdAt: agentLogChunks.createdAt,
      })
      .from(agentLogChunks)
      .where(eq(agentLogChunks.agentId, agentId))
      .orderBy(asc(agentLogChunks.createdAt));
  }

  async deleteByAgentId(agentId: string): Promise<void> {
    await this.db
      .delete(agentLogChunks)
      .where(eq(agentLogChunks.agentId, agentId));
  }

  async getSessionCount(agentId: string): Promise<number> {
    const result = await this.db
      .select({ maxSession: max(agentLogChunks.sessionNumber) })
      .from(agentLogChunks)
      .where(eq(agentLogChunks.agentId, agentId));

    return result[0]?.maxSession ?? 0;
  }
}
