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

/**
 * Enum for permission actions.
 * DDL uses VARCHAR(50) -- not a PostgreSQL enum -- but we keep this TS enum
 * for type safety.  Values must match the seed data in 07-users-rbac.sql.
 */
export enum PermissionAction {
  CREATE = 'create',
  READ = 'read',
  UPDATE = 'update',
  DELETE = 'delete',
  EXPORT = 'export',
}

/**
 * Entity: users.permissions
 * DDL source: database/ddl/07-users-rbac.sql
 *
 * Permisos granulares del sistema (resource.action.scope).
 * Global -- no tenant_id column.
 */
@Entity({ schema: 'users', name: 'permissions' })
@Unique(['resource', 'action', 'scope'])
@Index('idx_permissions_resource', ['resource'])
@Index('idx_permissions_category', ['category'])
export class Permission {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

  @Column({ type: 'varchar', length: 50, default: "'own'", nullable: true })
  scope: string;

  // Info
  @Column({ type: 'varchar', length: 255, nullable: true, name: 'display_name' })
  displayName: string | null;

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

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

  // Flags
  @Column({ type: 'boolean', default: false, name: 'is_dangerous' })
  isDangerous: boolean;

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

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