import {
  Column,
  CreateDateColumn,
  Entity,
  JoinColumn,
  ManyToOne,
  PrimaryColumn,
  UpdateDateColumn,
} from 'typeorm';
import { randomUUID } from 'crypto';
import { MonitorTargetEntity } from './monitor-target.entity';

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

  @Column({ name: 'target_id', type: 'varchar', length: 64 })
  targetId!: 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({ type: 'varchar', length: 255, nullable: true })
  summary!: string | null;

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

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

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

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

  @Column({
    name: 'result_json_url',
    type: 'varchar',
    length: 1024,
    nullable: true,
  })
  resultJsonUrl!: 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(() => MonitorTargetEntity, (target) => target.runs, {
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'target_id' })
  target!: MonitorTargetEntity;
}
