import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn, Check } from 'typeorm';
import { License } from './license.entity';
import { WipeSchedule } from './wipe-schedule.entity';
import { WipeProfile } from './wipe-profile.entity';
import { MapLibrary } from './map-library.entity';

@Entity('wipe_history')
@Check(`"wipe_type" IN ('map', 'blueprint', 'full')`)
@Check(`"trigger_type" IN ('scheduled', 'manual', 'force_wipe')`)
@Check(`"status" IN ('pending', 'pre_wipe', 'wiping', 'post_wipe', 'success', 'failed', 'rolled_back')`)
export class WipeHistory {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'uuid' })
  license_id: string;

  @Column({ type: 'uuid', nullable: true })
  wipe_schedule_id: string | null;

  @Column({ type: 'uuid' })
  wipe_profile_id: string;

  @Column({ type: 'varchar', length: 20 })
  wipe_type: string;

  @Column({ type: 'varchar', length: 20 })
  trigger_type: string;

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

  @Column({ type: 'timestamptz', nullable: true })
  started_at: Date | null;

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

  @Column({ type: 'varchar', length: 255, nullable: true })
  map_used_legacy: string | null;

  @Column({ type: 'uuid', nullable: true })
  map_id: string | null;

  @Column('text', { array: true, nullable: true })
  plugins_wiped: string[] | null;

  @Column('text', { array: true, nullable: true })
  plugins_preserved: string[] | null;

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

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

  @Column({ type: 'jsonb', default: '[]' })
  execution_log: any[];

  @Column({ type: 'timestamptz', default: () => 'NOW()' })
  created_at: Date;

  @ManyToOne(() => License, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'license_id' })
  license: License;

  @ManyToOne(() => WipeSchedule, { onDelete: 'SET NULL', nullable: true })
  @JoinColumn({ name: 'wipe_schedule_id' })
  wipe_schedule: WipeSchedule | null;

  @ManyToOne(() => WipeProfile)
  @JoinColumn({ name: 'wipe_profile_id' })
  wipe_profile: WipeProfile;

  @ManyToOne(() => MapLibrary, { onDelete: 'SET NULL', nullable: true })
  @JoinColumn({ name: 'map_id' })
  map: MapLibrary | null;
}
