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

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

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

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

  @Column({ name: 'service_key', type: 'varchar', length: 255 })
  serviceKey!: string;

  @Column({ type: 'varchar', length: 255 })
  title!: string;

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

  @Column({ type: 'varchar', length: 16 })
  severity!: 'info' | 'warning' | 'major' | 'critical';

  @Column({ type: 'varchar', length: 16, default: 'open' })
  status!: 'open' | 'acknowledged' | 'resolved';

  @Column({ name: 'source_type', type: 'varchar', length: 32 })
  sourceType!: 'run-status' | 'log-analysis';

  @Column({ type: 'text' })
  summary!: string;

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

  @Column({ name: 'first_detected_at', type: 'timestamp' })
  firstDetectedAt!: Date;

  @Column({ name: 'last_detected_at', type: 'timestamp' })
  lastDetectedAt!: Date;

  @Column({ name: 'occurrence_count', type: 'int', default: 1 })
  occurrenceCount!: number;

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

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

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

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

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

  @ManyToOne(() => MonitorTargetEntity, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'target_id' })
  target!: MonitorTargetEntity;

  @ManyToOne(() => MonitorRunEntity, { onDelete: 'SET NULL' })
  @JoinColumn({ name: 'run_id' })
  run!: MonitorRunEntity | null;
}
