import {
  Column,
  CreateDateColumn,
  Entity,
  JoinColumn,
  ManyToOne,
  PrimaryColumn,
  UpdateDateColumn,
} from 'typeorm';
import { randomUUID } from 'crypto';
import { InspectionTaskEntity } from '../tasks/inspection-task.entity';

@Entity({ name: 'inspection_run' })
export class InspectionRunEntity {
  @PrimaryColumn({ type: 'varchar', length: 64 })
  id: string = randomUUID();

  @Column({ name: 'task_id', type: 'varchar', length: 64 })
  taskId!: string;

  @Column({ name: 'trace_id', type: 'varchar', length: 128, unique: true })
  traceId!: string;

  @Column({ type: 'varchar', length: 16 })
  status!: 'queued' | 'running' | 'success' | 'failed' | 'partial';

  @Column({ name: 'error_tag', type: 'varchar', length: 64, nullable: true })
  errorTag!: string | null;

  @Column({ name: 'failure_reason', type: 'text', nullable: true })
  failureReason!: string | null;

  @Column({ name: 'screenshot_urls', type: 'text', nullable: true })
  screenshotUrls!: string | null;

  @Column({ name: 'step_logs_json', type: 'text', nullable: true })
  stepLogsJson!: string | null;

  @Column({ name: 'page_url', type: 'varchar', length: 1024, nullable: true })
  pageUrl!: string | null;

  @Column({ name: 'dom_summary', type: 'text', nullable: true })
  domSummary!: string | null;

  @Column({ type: 'varchar', length: 32, default: 'browser' })
  executor!: 'browser' | 'agent-s';

  @Column({ name: 'route_policy', type: 'varchar', length: 32, nullable: true })
  routePolicy!: string | null;

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

  @Column({ name: 'ended_at', type: 'timestamp', nullable: true })
  endedAt!: Date | null;

  @CreateDateColumn({ name: 'created_at' })
  createdAt!: Date;

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt!: Date;

  @ManyToOne(() => InspectionTaskEntity, (task) => task.runs, {
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'task_id' })
  task!: InspectionTaskEntity;
}
