import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  ManyToOne,
  OneToMany,
  JoinColumn,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
} from 'typeorm';
import { Standard } from '../../standards/entities/standard.entity';
import { ChecklistTemplateItem } from './checklist-template-item.entity';
import { User } from '../../user/entities/user.entity';

@Entity({ name: 'checklist_templates' })
export class ChecklistTemplate {
  @PrimaryGeneratedColumn()
  id: number;

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

  @Index()
  @Column({ type: 'int', nullable: true })
  standard_id: number | null;

  @ManyToOne(() => Standard, { nullable: true })
  @JoinColumn({ name: 'standard_id' })
  standard: Standard | null;

  // Multi-standard support: JSON array of standard IDs.
  // When set, this template applies to all listed standards.
  // Falls back to standard_id for templates created before this column.
  @Column({ type: 'json', nullable: true })
  standard_ids: number[] | null;

  @Column({ type: 'tinyint', width: 1, default: 0 })
  is_generic: boolean;

  // Who generated this template. Nullable so existing rows (created before
  // this column existed) don't break; treated as "no owner" → only visible
  // to users with the view-all permission, never matches a specific auditor.
  @Index()
  @Column({ type: 'int', nullable: true })
  created_by: number | null;

  @ManyToOne(() => User, { nullable: true })
  @JoinColumn({ name: 'created_by' })
  created_by_user: User | null;

  @OneToMany(() => ChecklistTemplateItem, (item) => item.template)
  items: ChecklistTemplateItem[];

  @CreateDateColumn()
  created_at: Date;

  @UpdateDateColumn()
  updated_at: Date;
}