/**
 * Access Log Entity
 * Historial de acceso a documentos.
 *
 * @module Documents (MAE-016)
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  ManyToOne,
  JoinColumn,
  Index,
} from 'typeorm';
import { Document } from './document.entity';
import { DocumentVersion } from './document-version.entity';
import { User } from '../../core/entities/user.entity';

@Entity('access_logs', { schema: 'documents' })
@Index(['tenantId'])
@Index(['documentId'])
@Index(['userId'])
@Index(['accessedAt'])
export class AccessLog {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

  @Column({ name: 'tenant_id', type: 'uuid' })
  tenantId!: string;

  // Documento
  @Column({ name: 'document_id', type: 'uuid' })
  documentId!: string;

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

  @Column({ name: 'version_id', type: 'uuid', nullable: true })
  versionId?: string;

  @ManyToOne(() => DocumentVersion, { nullable: true })
  @JoinColumn({ name: 'version_id' })
  version?: DocumentVersion;

  // Accion
  @Column({ length: 50 })
  action!: string; // view, download, print, share, edit

  @Column({ name: 'action_details', type: 'jsonb', nullable: true })
  actionDetails?: Record<string, any>;

  // Usuario
  @Column({ name: 'user_id', type: 'uuid' })
  userId!: string;

  @Column({ name: 'user_name', length: 255, nullable: true })
  userName?: string;

  @Column({ name: 'user_ip', length: 45, nullable: true })
  userIp?: string;

  @Column({ name: 'user_agent', type: 'text', nullable: true })
  userAgent?: string;

  // Contexto
  @Column({ name: 'session_id', length: 100, nullable: true })
  sessionId?: string;

  @Column({ name: 'request_source', length: 50, nullable: true })
  requestSource?: string; // web, mobile, api

  // Timestamp
  @Column({ name: 'accessed_at', type: 'timestamptz', default: () => 'NOW()' })
  accessedAt!: Date;

  // FK a auth.users (ERP-Core) - usuario que accedió
  @ManyToOne(() => User, { nullable: true })
  @JoinColumn({ name: 'user_id' })
  user?: User;
}
