import {
  Column,
  CreateDateColumn,
  Entity,
  Index,
  JoinColumn,
  ManyToOne,
  OneToMany,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from 'typeorm';

import { User } from '../../user/entities/user.entity';
import { DocumentRoleAssignment } from './document-role-assignment.entity';

export enum DocumentStatus {
  ACTIVE = 'active',
  ARCHIVED = 'archived',
}

@Entity('documents')
@Index(['category'])
@Index(['status'])
@Index(['uploaded_by'])
export class Document {
  @PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
  id: number;

  // ─── Metadata ────────────────────────────────────────────────────────
  @Column({ type: 'varchar', length: 200 })
  title: string;

  @Column({ type: 'varchar', length: 100 })
  category: string; // ISO Documentation | Audit Reports | Marketing | HR & Policies | Certificates

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

  // ─── File on disk (same convention as audit_files / audit-requests) ──
  @Column({ type: 'varchar', length: 500 })
  file_path: string;

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

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

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

  // ─── Security ────────────────────────────────────────────────────────
  // bcrypt hash — NULL means no password required
  @Column({ type: 'varchar', length: 255, nullable: true })
  password_hash: string | null;

  @Column({ type: 'tinyint', width: 1, default: 1 })
  require_otp: number; // 1 = require email OTP, 0 = no OTP

  @Column({ type: 'tinyint', width: 1, default: 1 })
  allow_download: number; // 0 = view-only

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

  // ─── Status + audit trail ────────────────────────────────────────────
  @Column({
    type: 'enum',
    enum: DocumentStatus,
    default: DocumentStatus.ACTIVE,
  })
  status: DocumentStatus;

  @Column({ type: 'int' })
  uploaded_by: number;

  @ManyToOne(() => User)
  @JoinColumn({ name: 'uploaded_by' })
  uploader: User;

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

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

  // ─── Relations ───────────────────────────────────────────────────────
  @OneToMany(() => DocumentRoleAssignment, (a) => a.document, { cascade: true })
  role_assignments: DocumentRoleAssignment[];
}
