import { ObjectOwner } from '@mysten/sui/client'

import { MoveCallWithObjectDetails } from './move-call-object-fetcher'
import { IPTBValidator } from './ptb-validator'

/**
 * ShareObjectValidator ensures all object arguments are Shared or Immutable
 * This is the default validator for PTB operations
 */
export class ShareObjectValidator implements IPTBValidator {
    /**
     * Validates move calls with pre-fetched object details
     * @param moveCallsWithDetails - Array of move calls with object details
     * @throws Error if any object is not Shared/Immutable
     */
    validate(moveCallsWithDetails: MoveCallWithObjectDetails[]): void {
        for (const { objectDetails } of moveCallsWithDetails) {
            for (const [objectId, objectResponse] of objectDetails) {
                if (objectResponse.data?.owner == null) {
                    throw new Error(`Object ${objectId} does not have owner`)
                }
                if (!this.isSharedOrImmutable(objectResponse.data.owner)) {
                    throw new Error(`Object ${objectId} is not Shared/Immutable`)
                }
            }
        }
    }

    /**
     * Checks if an object owner is Shared or Immutable
     * @param owner - The object owner to check
     * @returns true if the owner is Shared or Immutable, false otherwise
     */
    protected isSharedOrImmutable(owner: ObjectOwner): boolean {
        return (typeof owner === 'object' && 'Shared' in owner) || owner === 'Immutable'
    }
}
