import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  ManyToOne,
  CreateDateColumn,
  UpdateDateColumn,
  JoinColumn,
} from 'typeorm';
import { Standard } from '../../standards/entities/standard.entity';

@Entity('training_certificate')
export class TrainingCertificate {
  @PrimaryGeneratedColumn()
  id: number;

  /** RELATIONSHIPS **/
  // Optional link to the ISO standard the training covered (e.g. ISO 45001)
  @ManyToOne(() => Standard, { nullable: true })
  @JoinColumn({ name: 'standard_id' })
  standard: Standard | null;

  /** PARTICIPANT (a person — not a client company) **/
  @Column({ type: 'varchar', length: 255 })
  participant_name: string;

  // Participant's employer — plain text, they may not be a QRS client
  @Column({ type: 'varchar', length: 255, nullable: true })
  participant_company: string | null;

  /** TRAINING DETAILS **/
  // e.g. "ISO 45001:2018 Awareness & Internal Audit Training"
  @Column({ type: 'varchar', length: 255 })
  course_title: string;

  // e.g. "Abu Dhabi, UAE"
  @Column({ type: 'varchar', length: 255 })
  training_location: string;

  @Column({ type: 'date' })
  training_date: Date;

  // Optional second date — for multi-day trainings (e.g. "6 and 7 July 2026")
  @Column({ type: 'date', nullable: true })
  training_date_end: Date | null;

  // Optional expiry — NULL means the certificate never expires
  @Column({ type: 'date', nullable: true })
  valid_until: Date | null;

  /** CERTIFICATE IDENTIFIERS **/
  // Auto-generated as QRS-TRG-{YY}-{NNN} (e.g. QRS-TRG-26-001), manual override allowed
  @Column({ type: 'varchar', length: 30, unique: true })
  certificate_no: string;

  @Column({ type: 'varchar', length: 36, unique: true })
  qrcode_token: string;

  @Column({ type: 'varchar', length: 50, nullable: true })
  fingerprint: string;

  @Column({
    type: 'enum',
    enum: ['local', 'international'],
    default: 'local',
  })
  verification_domain: string;

  // Groups certificates issued together in one training session (batch issue)
  @Column({ type: 'varchar', length: 50, nullable: true })
  batch_ref: string | null;

  /** UPLOADED SIGNED SCAN — the only PDF (no template generation) **/
  @Column({ type: 'varchar', length: 500, nullable: true })
  scan_pdf_url: string;

  @Column({ type: 'timestamp', nullable: true })
  scan_uploaded_at: Date;

  @Column({ type: 'int', nullable: true })
  scan_uploaded_by: number;

  /** STATUS — starts pending_scan, becomes active when the scan is uploaded **/
  @Column({
    type: 'enum',
    enum: ['pending_scan', 'active', 'expired', 'revoked', 'fake'],
    default: 'pending_scan',
  })
  status: string;

  /** AUDIT **/
  @Column({ type: 'int', nullable: true })
  created_by: number;

  @Column({ type: 'int', nullable: true })
  updated_by: number;

  @CreateDateColumn()
  created_at: Date;

  @UpdateDateColumn()
  updated_at: Date;
}