import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
  ManyToMany,
} from 'typeorm';
import { Role } from './role.entity.js';

export enum PermissionAction {
  CREATE = 'create',
  READ = 'read',
  UPDATE = 'update',
  DELETE = 'delete',
  APPROVE = 'approve',
  CANCEL = 'cancel',
  EXPORT = 'export',
}

@Entity({ schema: 'auth', name: 'permissions' })
@Index('idx_permissions_resource', ['resource'])
@Index('idx_permissions_action', ['action'])
@Index('idx_permissions_module', ['module'])
export class Permission {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'varchar', length: 100, nullable: false })
  resource: string;

  @Column({
    type: 'enum',
    enum: PermissionAction,
    nullable: false,
  })
  action: PermissionAction;

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

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

  // Relaciones
  @ManyToMany(() => Role, (role) => role.permissions)
  roles: Role[];

  // Sin tenant_id: permisos son globales
  @CreateDateColumn({ name: 'created_at', type: 'timestamp' })
  createdAt: Date;
}
