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

export type PermissionChangeType = 'role_assigned' | 'role_revoked' | 'permission_granted' | 'permission_revoked';
export type PermissionScope = 'global' | 'tenant' | 'branch';

@Entity({ name: 'permission_changes', schema: 'audit' })
export class PermissionChange {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ name: 'changed_by', type: 'uuid' })
  changedBy: string;

  @Index()
  @Column({ name: 'target_user_id', type: 'uuid' })
  targetUserId: string;

  @Column({ name: 'target_user_email', type: 'varchar', length: 255, nullable: true })
  targetUserEmail: string;

  @Column({ name: 'change_type', type: 'varchar', length: 30 })
  changeType: PermissionChangeType;

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

  @Column({ name: 'role_code', type: 'varchar', length: 50, nullable: true })
  roleCode: string;

  @Column({ name: 'permission_id', type: 'uuid', nullable: true })
  permissionId: string;

  @Column({ name: 'permission_code', type: 'varchar', length: 100, nullable: true })
  permissionCode: string;

  @Column({ name: 'branch_id', type: 'uuid', nullable: true })
  branchId: string;

  @Column({ name: 'scope', type: 'varchar', length: 30, nullable: true })
  scope: PermissionScope;

  @Column({ name: 'previous_roles', type: 'text', array: true, nullable: true })
  previousRoles: string[];

  @Column({ name: 'previous_permissions', type: 'text', array: true, nullable: true })
  previousPermissions: string[];

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

  @Index()
  @Column({ name: 'changed_at', type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
  changedAt: Date;
}
