import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  OneToMany,
  Index,
} from 'typeorm';
import { NcrEntryEntity } from './ncr-entry.entity';
import { NcRemarkEntity } from './nc-remark.entity';

/**
 * nc__ncs in scheme_dbs s — a NEW non-conformity raised by an auditor from a
 * scheduled audit. Distinct from PreviousNcEntity, which maps the same table
 * name in the old qrs/tqs databases.
 *
 * Relationship: nc.audit_id → audit_schedule_rows.id (the My Audits row).
 */
@Entity({ name: 'nc__ncs' })
export class NcEntity {
  @PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
  id: number;

  @Index()
  @Column({ type: 'int' })
  audit_id: number; // = audit_schedule_rows.id

  @Index()
  @Column({ type: 'int', nullable: true })
  company_id: number | null; // = companies.id (denormalized from the audit)

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

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

  @Column({ type: 'varchar', length: 50 })
  nc_type: string; // Major / Minor / Observation

  @Index()
  @Column({ type: 'varchar', length: 20, default: 'open' })
  status: string; // open / closed

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

  @Column({ type: 'bigint', unsigned: true, nullable: true })
  followed_up_by: number | null;

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

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

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

  @Column({ type: 'bigint', unsigned: true, nullable: true })
  closed_by: number | null;

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

  @Column({ type: 'bigint', unsigned: true, nullable: true })
  created_by: number | null; // the auditor who raised it

  @CreateDateColumn({ type: 'datetime' })
  created_at: Date;

  @UpdateDateColumn({ type: 'datetime' })
  updated_at: Date;

  // ── Relations ──────────────────────────────────────────────────
  @OneToMany(() => NcrEntryEntity, (e) => e.nc, { cascade: ['insert'] })
  entries: NcrEntryEntity[];

  @OneToMany(() => NcRemarkEntity, (r) => r.nc, { cascade: ['insert'] })
  remarks: NcRemarkEntity[];
}
