import {
  Column,
  CreateDateColumn,
  Entity,
  Index,
  JoinColumn,
  ManyToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { AiMessage } from './ai-message.entity';

export type AiToolRunStatus = 'running' | 'success' | 'failed' | 'denied' | 'not_found';

@Entity('ai_tool_runs')
@Index('idx_ai_tool_runs_message', ['messageId'])
export class AiToolRun {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: 'message_id', type: 'integer' })
  messageId: number;

  @ManyToOne(() => AiMessage, (message) => message.toolRuns, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'message_id' })
  message: AiMessage;

  @Column({ name: 'tool_call_id', type: 'varchar', length: 100 })
  toolCallId: string;

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

  @Column({ name: 'skill_key', type: 'varchar', length: 50, nullable: true })
  skillKey: string | null;

  @Column({ name: 'arguments_summary', type: 'text', nullable: true })
  argumentsSummary: string | null;

  @Column({ name: 'result_summary', type: 'text', nullable: true })
  resultSummary: string | null;

  @Column({ name: 'arguments_data', type: 'simple-json', nullable: true })
  argumentsData: Record<string, unknown> | null;

  @Column({ name: 'result_data', type: 'simple-json', nullable: true })
  resultData: Record<string, unknown> | unknown[] | null;

  @Column({ type: 'varchar', length: 20 })
  status: AiToolRunStatus;

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

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