import { Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { TenantAwareRepository } from '@it0/database';
import { AgentTask } from '../../domain/entities/agent-task.entity';
import { TaskStatus } from '../../domain/value-objects/task-status.vo';

@Injectable()
export class TaskRepository extends TenantAwareRepository<AgentTask> {
  constructor(dataSource: DataSource) {
    super(dataSource, AgentTask);
  }

  async findBySessionId(sessionId: string): Promise<AgentTask[]> {
    return this.withRepository((repo) =>
      repo.find({ where: { sessionId } as any }),
    );
  }

  async findRunningBySessionId(sessionId: string): Promise<AgentTask | null> {
    return this.withRepository((repo) =>
      repo.findOne({
        where: { sessionId, status: TaskStatus.RUNNING } as any,
        order: { createdAt: 'DESC' } as any,
      }),
    );
  }
}
