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

import { Document } from './document.entity';

export enum DocumentAction {
  VIEWED = 'viewed',
  DOWNLOADED = 'downloaded',
  OTP_SENT = 'otp_sent',
  OTP_FAILED = 'otp_failed',
  PASSWORD_FAILED = 'password_failed',
  DENIED = 'denied',
}

/**
 * Full audit trail. Every open, download and failed attempt lands here.
 * Never deleted — even if the parent document is archived.
 */
@Entity('document_access_log')
@Index(['document_id'])
@Index(['user_id'])
@Index(['action'])
export class DocumentAccessLog {
  @PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
  id: number;

  @Column({ type: 'bigint', unsigned: true })
  document_id: number;

  @ManyToOne(() => Document, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'document_id' })
  document: Document;

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

  // Denormalised snapshots — so the log stays readable if user is later renamed / removed
  @Column({ type: 'varchar', length: 150, nullable: true })
  user_name: string | null;

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

  @Column({ type: 'enum', enum: DocumentAction })
  action: DocumentAction;

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

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

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