import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
  OneToOne,
} from 'typeorm';
import { ToolCallResult } from './tool-call-result.entity';
import { CallerType } from '../interfaces';

export type ToolCallStatus = 'pending' | 'running' | 'success' | 'error' | 'timeout';

@Entity({ name: 'tool_calls', schema: 'ai' })
export class ToolCall {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'tenant_id', type: 'uuid' })
  tenantId: string;

  @Index()
  @Column({ name: 'agent_id', type: 'uuid', nullable: true })
  agentId: string;

  @Index()
  @Column({ name: 'conversation_id', type: 'uuid', nullable: true })
  conversationId: string;

  @Index()
  @Column({ name: 'tool_name', type: 'varchar', length: 100 })
  toolName: string;

  @Column({ type: 'jsonb', default: {} })
  parameters: Record<string, any>;

  @Index()
  @Column({ type: 'varchar', length: 20, default: 'pending' })
  status: ToolCallStatus;

  @Column({ name: 'duration_ms', type: 'int', nullable: true })
  durationMs: number;

  @Column({ name: 'started_at', type: 'timestamptz' })
  startedAt: Date;

  @Column({ name: 'completed_at', type: 'timestamptz', nullable: true })
  completedAt: Date;

  @Column({ name: 'called_by_user_id', type: 'uuid', nullable: true })
  calledByUserId: string;

  @Column({ name: 'caller_type', type: 'varchar', length: 20, default: 'agent' })
  callerType: CallerType;

  @Column({ name: 'caller_context', type: 'varchar', length: 100, nullable: true })
  callerContext: string;

  @CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
  createdAt: Date;

  @OneToOne(() => ToolCallResult, (result) => result.toolCall)
  result: ToolCallResult;
}
