const SCHEMA_VERSION = 2;

export class FactionSeatModel {
    static SCHEMA_VERSION = SCHEMA_VERSION;

    static create(factionNode, placeNode) {
        const endpoints = this.resolveEndpoints(factionNode, placeNode);
        if (!endpoints) return null;
        return {
            schemaVersion: SCHEMA_VERSION,
            factionNodeId: endpoints.factionNode.id,
            placeNodeId: endpoints.placeNode.id
        };
    }

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

    static canRepresent(leftNode = {}, rightNode = {}) {
        return !!this.resolveEndpoints(leftNode, rightNode);
    }

    static resolveEndpoints(leftNode = {}, rightNode = {}) {
        const leftFaction = this.#isEntityType(leftNode, "faction");
        const rightFaction = this.#isEntityType(rightNode, "faction");
        const leftPlace = this.#isPlace(leftNode);
        const rightPlace = this.#isPlace(rightNode);
        if (leftFaction && rightPlace) return { factionNode: leftNode, placeNode: rightNode };
        if (rightFaction && leftPlace) return { factionNode: rightNode, placeNode: leftNode };
        return null;
    }

    static isSeat(edge = {}) {
        return !!edge?.factionSeat && typeof edge.factionSeat === "object";
    }

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

    static #isPlace(node = {}) {
        return node?.kind === "nexus-site"
            || node?.kind === "nexus-scene"
            || this.#isEntityType(node, "location");
    }
}
