/*
 * @module subscription helper/util/etc. functions
 *
 * this is where you will find helper functions like those that generate
 * and parse ibs for subscription.
 */
// import * as pathUtils from 'path';
// import { statSync } from 'node:fs';
// import { readFile, } from 'node:fs/promises';
// import * as readline from 'node:readline/promises';
// import { stdin, stdout } from 'node:process'; // decide if use this or not
import { extractErrorMsg, } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';
import { UUID_REGEXP, CLASSNAME_REGEXP, } from '@ibgib/helper-gib/dist/constants.mjs';
import { validateIbGibIntrinsically, } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';
import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs';
import { WitnessFormBuilder } from '../../../witness/witness-form-builder.mjs';
import { SUBSCRIPTION_ATOM, SUBSCRIPTION_NAME_REGEXP, } from './subscription-constants.mjs';
import { Subscription_V1_Factory } from './subscription-v1.mjs';
/**
 * for logging. import this constant from your project.
 */
const logalot = GLOBAL_LOG_A_LOT;
export function validateCommonSubscriptionData({ data, }) {
    const lc = `[${validateCommonSubscriptionData.name}]`;
    try {
        if (logalot) {
            console.log(`${lc} starting...`);
        }
        if (!data) {
            throw new Error(`Subscription Data required (E: 6d1c97931dcab8ea9f3e9b32c794b90c)`);
        }
        const errors = [];
        const { name, uuid, classname, } = data;
        if (name) {
            if (!name.match(SUBSCRIPTION_NAME_REGEXP)) {
                errors.push(`name must match regexp: ${SUBSCRIPTION_NAME_REGEXP} (E: 21bf77e398d47e9d035376510505eda2)`);
            }
        }
        else {
            errors.push(`name required.`);
        }
        if (uuid) {
            if (!uuid.match(UUID_REGEXP)) {
                errors.push(`uuid must match regexp: ${UUID_REGEXP} (E: e53fd08ae69e945b37ed895b864b6bd7)`);
            }
        }
        else {
            errors.push(`uuid required.`);
        }
        if (classname) {
            if (!classname.match(CLASSNAME_REGEXP)) {
                errors.push(`classname must match regexp: ${CLASSNAME_REGEXP}`);
            }
        }
        return errors;
    }
    catch (error) {
        console.error(`${lc} ${extractErrorMsg(error)}`);
        throw error;
    }
    finally {
        if (logalot) {
            console.log(`${lc} complete.`);
        }
    }
}
export async function validateCommonSubscriptionIbGib({ ibGib, }) {
    const lc = `[${validateCommonSubscriptionIbGib.name}]`;
    try {
        if (logalot) {
            console.log(`${lc} starting... (I: 53696a50efff60fd86a2f431dae6ac67)`);
        }
        const intrinsicErrors = await validateIbGibIntrinsically({ ibGib }) ?? [];
        if (!ibGib.data) {
            throw new Error(`ibGib.data required (E: 5bae607c41ed4de40ec333a40673bdb8)`);
        }
        const ibErrors = [];
        let { SubscriptionClassname, SubscriptionName, SubscriptionId } = parseSubscriptionIb({ ib: ibGib.ib });
        if (!SubscriptionClassname) {
            ibErrors.push(`SubscriptionClassname required (E: 029f7a2405c4b7aa1f52711586f8ebfd)`);
        }
        if (!SubscriptionName) {
            ibErrors.push(`SubscriptionName required (E: e68cbc6f3183169c35117184f610573e)`);
        }
        if (!SubscriptionId) {
            ibErrors.push(`SubscriptionId required (E: 0516442854be7ec32f5928b4cf2697f7)`);
        }
        const dataErrors = validateCommonSubscriptionData({ data: ibGib.data });
        let result = [...(intrinsicErrors ?? []), ...(ibErrors ?? []), ...(dataErrors ?? [])];
        if (result.length > 0) {
            return result;
        }
        else {
            return undefined;
        }
    }
    catch (error) {
        console.error(`${lc} ${extractErrorMsg(error)}`);
        throw error;
    }
    finally {
        if (logalot) {
            console.log(`${lc} complete.`);
        }
    }
}
export function getSubscriptionIb({ data, classname, }) {
    const lc = `[${getSubscriptionIb.name}]`;
    try {
        const validationErrors = validateCommonSubscriptionData({ data });
        if (validationErrors.length > 0) {
            throw new Error(`invalid Subscription data: ${validationErrors} (E: fd6b0b32d8f6c4b97eebd489cdb07a4a)`);
        }
        if (classname) {
            if (data.classname && data.classname !== classname) {
                throw new Error(`classname does not match data.classname (E: 354285a56a20b9b65b06abfcd9f2e621)`);
            }
        }
        else {
            classname = data.classname;
            if (!classname) {
                throw new Error(`classname required (E: 040c1fd71853fa7874146999afb355c3)`);
            }
        }
        // ad hoc validation here. should centralize witness classname validation
        const { uuid } = data;
        // uuid is instanceId (atow 11/2023)
        return `witness ${SUBSCRIPTION_ATOM} ${classname} ${uuid}`;
    }
    catch (error) {
        console.error(`${lc} ${extractErrorMsg(error)}`);
        throw error;
    }
}
/**
 * Current schema is 'witness [SUBSCRIPTION_ATOM] [classname] [SubscriptionName] [SubscriptionId]'
 *
 * NOTE this is space-delimited
 */
export function parseSubscriptionIb({ ib, }) {
    const lc = `[${parseSubscriptionIb.name}]`;
    try {
        if (!ib) {
            throw new Error(`Subscription ib required (E: 84156af64e73d479220a36f247466659)`);
        }
        const pieces = ib.split(' ');
        return {
            SubscriptionClassname: pieces[2],
            SubscriptionName: pieces[3],
            SubscriptionId: pieces[4],
        };
    }
    catch (error) {
        console.error(`${lc} ${extractErrorMsg(error)}`);
        throw error;
    }
}
export class SubscriptionFormBuilder extends WitnessFormBuilder {
    lc = `[${SubscriptionFormBuilder.name}]`;
    constructor() {
        super();
        this.what = 'subscription';
    }
}
export function isSubscription({ ibGib, }) {
    const lc = `[${isSubscription.name}]`;
    try {
        if (logalot) {
            console.log(`${lc} starting... (I: 43df7e7f61f25e65662ce8aa5a105a23)`);
        }
        if (!ibGib) {
            return false;
        }
        let sub = ibGib;
        return typeof sub.witness === 'function' &&
            typeof sub.unsubscribe === 'function' &&
            typeof sub.unsubscribed === 'function';
    }
    catch (error) {
        console.error(`${lc} ${error.message}`);
        throw error;
    }
    finally {
        if (logalot) {
            console.log(`${lc} complete.`);
        }
    }
}
// #region sugar
/**
 * Uses {@link Subscription_V1_Factory} to new up a blank subscription.
 * @returns subscription
 */
export async function newupSubscription() {
    const subscriptionFactory = new Subscription_V1_Factory();
    return (await subscriptionFactory.newUp({})).newIbGib;
}
// #endregion sugar
//# sourceMappingURL=subscription-helper.mjs.map