import { NotFoundException, ForbiddenException } from '@nestjs/common';

export interface OwnedEntity {
  organizationId: string;
  createdById: string | null;
}

export interface AssertOwnOptions {
  entityLabel: string;
  /** true 时 createdById=null 视为系统资源，任何用户都可读/软改（personas 系统预设语义） */
  allowSystemOwner?: boolean;
}

export function assertOwn<T extends OwnedEntity>(
  entity: T | null,
  organizationId: string,
  userId: string,
  options: AssertOwnOptions,
): T {
  const { entityLabel, allowSystemOwner = false } = options;
  if (!entity) throw new NotFoundException(`${entityLabel} not found`);
  if (entity.organizationId !== organizationId) {
    throw new ForbiddenException('cross-org access denied');
  }
  if (entity.createdById === null) {
    if (allowSystemOwner) return entity;
    throw new ForbiddenException(`not ${entityLabel} owner`);
  }
  if (entity.createdById !== userId) {
    throw new ForbiddenException(`not ${entityLabel} owner`);
  }
  return entity;
}
