/**
 * Document Permission Entity
 * Permisos granulares por documento o categoria.
 *
 * @module Documents (MAE-016)
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  JoinColumn,
  Index,
} from 'typeorm';
import { Document } from './document.entity';
import { DocumentCategory } from './document-category.entity';

@Entity('document_permissions', { schema: 'documents' })
@Index(['documentId'])
@Index(['categoryId'])
@Index(['userId'])
@Index(['roleId'])
export class DocumentPermission {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

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

  // Objeto (documento o categoria)
  @Column({ name: 'document_id', type: 'uuid', nullable: true })
  documentId?: string;

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

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

  @ManyToOne(() => DocumentCategory, { nullable: true, onDelete: 'CASCADE' })
  @JoinColumn({ name: 'category_id' })
  category?: DocumentCategory;

  // Sujeto (quien tiene el permiso)
  @Column({ name: 'user_id', type: 'uuid', nullable: true })
  userId?: string;

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

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

  // Permisos
  @Column({ name: 'can_view', type: 'boolean', default: false })
  canView!: boolean;

  @Column({ name: 'can_download', type: 'boolean', default: false })
  canDownload!: boolean;

  @Column({ name: 'can_edit', type: 'boolean', default: false })
  canEdit!: boolean;

  @Column({ name: 'can_delete', type: 'boolean', default: false })
  canDelete!: boolean;

  @Column({ name: 'can_share', type: 'boolean', default: false })
  canShare!: boolean;

  @Column({ name: 'can_approve', type: 'boolean', default: false })
  canApprove!: boolean;

  @Column({ name: 'can_annotate', type: 'boolean', default: false })
  canAnnotate!: boolean;

  // Vigencia
  @Column({ name: 'valid_from', type: 'timestamptz', nullable: true })
  validFrom?: Date;

  @Column({ name: 'valid_until', type: 'timestamptz', nullable: true })
  validUntil?: Date;

  // Otorgado por
  @Column({ name: 'granted_by_id', type: 'uuid', nullable: true })
  grantedById?: string;

  @Column({ name: 'granted_at', type: 'timestamptz', default: () => 'NOW()' })
  grantedAt!: Date;

  // Auditoria
  @CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
  createdAt!: Date;

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
  updatedAt!: Date;
}
