const SCHEMA_VERSION = 1;

export class ShipOwnershipModel {
    static SCHEMA_VERSION = SCHEMA_VERSION;

    static create(shipNode, ownerNode, { managedConnection = false, previousViews = null } = {}) {
        const endpoints = this.resolveEndpoints(shipNode, ownerNode);
        if (!endpoints) return null;
        return {
            schemaVersion: SCHEMA_VERSION,
            shipNodeId: endpoints.shipNode.id,
            ownerNodeId: endpoints.ownerNode.id,
            managedConnection: managedConnection === true,
            previousViews: previousViews && typeof previousViews === "object"
                ? foundry.utils.deepClone(previousViews)
                : null
        };
    }

    static normalize(value, { sourceNode = null, targetNode = null } = {}) {
        if (!value || typeof value !== "object" || Array.isArray(value)) return null;
        return this.create(sourceNode, targetNode, value);
    }

    static resolveEndpoints(leftNode = {}, rightNode = {}) {
        const leftShip = this.#isEntity(leftNode, "ship");
        const rightShip = this.#isEntity(rightNode, "ship");
        const leftOwner = this.#isOwner(leftNode);
        const rightOwner = this.#isOwner(rightNode);
        if (leftShip && rightOwner) return { shipNode: leftNode, ownerNode: rightNode };
        if (rightShip && leftOwner) return { shipNode: rightNode, ownerNode: leftNode };
        return null;
    }

    static isOwnership(edge = {}) {
        return !!edge?.shipOwnership;
    }

    static #isOwner(node = {}) {
        return this.#isEntity(node, "npc") || this.#isEntity(node, "faction");
    }

    static #isEntity(node = {}, entityType = "") {
        return node?.kind === "nexus-entity" && node.entityType === entityType && !!node.id;
    }
}
