"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsanaDbClient = void 0;
const net = __importStar(require("net"));
const document_js_1 = require("./document.js");
/**
 * Client for the AsanagiDB Compository (document store).
 *
 * Connects to asanadb via plain TCP on the configured host/port (default 127.0.0.1:8080).
 * Protocol: newline-delimited JSON. Node.js only (not browser-compatible).
 *
 * Documents returned by this client are pre-bound so you can call
 * {@link Document.save}, {@link Document.fetch}, {@link Document.update},
 * {@link Document.delete} on them without passing the client again.
 *
 * @example
 * const client = new AsanaDbClient();
 * await client.connect();
 * await client.useDatabase('mydb');
 *
 * const id = BigInt(Date.now());
 * const doc = new Document('Article', '_id', id)
 *   .add('title', 'Hello World')
 *   .add('body',  'My first Compository document.');
 * await client.insertOne(doc);
 *
 * const found = await client.findById(id);
 * console.log(found?.getString('title')); // Hello World
 * await client.close();
 */
class AsanaDbClient {
    socket = null;
    pending = [];
    buffer = '';
    async connect(host = '127.0.0.1', port = 8080) {
        return new Promise((resolve, reject) => {
            const sock = net.createConnection({ host, port }, () => {
                this.socket = sock;
                resolve();
            });
            sock.setEncoding('utf8');
            sock.on('data', (chunk) => {
                this.buffer += chunk;
                let nl;
                while ((nl = this.buffer.indexOf('\n')) !== -1) {
                    const line = this.buffer.slice(0, nl);
                    this.buffer = this.buffer.slice(nl + 1);
                    this.pending.shift()?.(line);
                }
            });
            sock.on('error', reject);
            sock.on('close', () => { this.socket = null; });
        });
    }
    async close() {
        return new Promise((resolve) => {
            if (!this.socket)
                return resolve();
            this.socket.end(resolve);
        });
    }
    /** Switch the active database (tenant). */
    async useDatabase(name) {
        await this.send({ op: 'use', database: name });
    }
    /**
     * Store a Document. Uses {@link Document.clazz} as the vertex label and
     * {@link Document.id} as the vertex ID (when set).
     */
    async insertOne(doc) {
        const id = doc.id;
        const req = { op: 'store', label: doc.clazz, entity: doc.toJSON() };
        if (id !== undefined)
            req['id'] = Number(id);
        const msg = await this.send(req);
        // Server returns the assigned vertex ID as a JSON number.
        if (typeof msg === 'number') {
            doc._id = BigInt(msg);
            doc.syncInternalFields();
        }
        doc._client = this;
        return { insertedId: doc.id };
    }
    /** Deep-fetch a Document by its internal vertex ID. Returns null if not found. */
    async findById(id) {
        const msg = await this.send({ op: 'retrieve', id: Number(id) });
        if (msg === null || typeof msg !== 'object' || Array.isArray(msg))
            return null;
        const doc = document_js_1.Document.fromObject(msg);
        doc._client = this;
        return doc;
    }
    /** Deep-fetch a Document by an indexed property key/value (e.g. the _key field). Returns null if not found. */
    async findByKey(key, value) {
        const wire = typeof value === 'bigint' ? Number(value) : value;
        const msg = await this.send({ op: 'retrieve', key, value: wire });
        if (msg === null || typeof msg !== 'object' || Array.isArray(msg))
            return null;
        const doc = document_js_1.Document.fromObject(msg);
        doc._client = this;
        return doc;
    }
    /** Replace an existing Document in-place by ID. */
    async replaceOne(id, doc) {
        const payload = { ...doc.toJSON(), [document_js_1.Document.name]: undefined, _id: Number(id) };
        await this.send({ op: 'store', entity: payload, id: Number(id) });
    }
    /** Delete a Document by its internal vertex ID. */
    async deleteOne(id) {
        await this.send({ op: 'delete', id: Number(id) });
    }
    /**
     * Return a shallow listing of all vertices. Each Document contains only
     * identifying fields (_id, _class, key field). Use {@link findById} for full content.
     */
    async listAll() {
        const msg = await this.send({ op: 'ls' });
        if (!Array.isArray(msg))
            return [];
        return msg.map((item) => {
            const doc = document_js_1.Document.fromObject(item);
            doc._client = this;
            return doc;
        });
    }
    send(request) {
        return new Promise((resolve, reject) => {
            if (!this.socket) {
                return reject(new Error('Not connected — call connect() first'));
            }
            this.pending.push((line) => {
                try {
                    const resp = JSON.parse(line);
                    if (resp.status !== 'ok') {
                        reject(new document_js_1.AsanaDbError(typeof resp.message === 'string' ? resp.message : 'Unknown error'));
                    }
                    else {
                        resolve(resp.message ?? null);
                    }
                }
                catch (e) {
                    reject(e);
                }
            });
            this.socket.write(JSON.stringify(request) + '\n', 'utf8', (err) => {
                if (err) {
                    this.pending.pop();
                    reject(err);
                }
            });
        });
    }
}
exports.AsanaDbClient = AsanaDbClient;
//# sourceMappingURL=client.js.map
