var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import { Resolver, Mutation, Arg, Ctx, ObjectType, Field, Int, InputType, PubSub, PubSubEngine } from 'type-graphql';
import { LogError, LogStatus, CompositeKey } from '@memberjunction/core';
import { ResolverBase } from '../generic/ResolverBase.js';
import { VersionHistoryEngine } from '@memberjunction/version-history';
import { KeyValuePairInput } from '../generic/KeyValuePairInput.js';
import { PUSH_STATUS_UPDATES_TOPIC } from '../generic/PushStatusResolver.js';
// =========================================================================
// GraphQL types
// =========================================================================
let CaptureErrorOutput = class CaptureErrorOutput {
};
__decorate([
    Field(),
    __metadata("design:type", String)
], CaptureErrorOutput.prototype, "EntityName", void 0);
__decorate([
    Field(),
    __metadata("design:type", String)
], CaptureErrorOutput.prototype, "RecordID", void 0);
__decorate([
    Field(),
    __metadata("design:type", String)
], CaptureErrorOutput.prototype, "ErrorMessage", void 0);
CaptureErrorOutput = __decorate([
    ObjectType()
], CaptureErrorOutput);
export { CaptureErrorOutput };
let CreateLabelResultOutput = class CreateLabelResultOutput {
};
__decorate([
    Field(),
    __metadata("design:type", Boolean)
], CreateLabelResultOutput.prototype, "Success", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], CreateLabelResultOutput.prototype, "LabelID", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], CreateLabelResultOutput.prototype, "LabelName", void 0);
__decorate([
    Field(() => Int, { nullable: true }),
    __metadata("design:type", Number)
], CreateLabelResultOutput.prototype, "ItemsCaptured", void 0);
__decorate([
    Field(() => Int, { nullable: true }),
    __metadata("design:type", Number)
], CreateLabelResultOutput.prototype, "SyntheticSnapshotsCreated", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], CreateLabelResultOutput.prototype, "Error", void 0);
__decorate([
    Field(() => [CaptureErrorOutput], { nullable: true }),
    __metadata("design:type", Array)
], CreateLabelResultOutput.prototype, "CaptureErrors", void 0);
CreateLabelResultOutput = __decorate([
    ObjectType()
], CreateLabelResultOutput);
export { CreateLabelResultOutput };
let CreateVersionLabelInput = class CreateVersionLabelInput {
};
__decorate([
    Field(),
    __metadata("design:type", String)
], CreateVersionLabelInput.prototype, "Name", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], CreateVersionLabelInput.prototype, "Description", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], CreateVersionLabelInput.prototype, "Scope", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], CreateVersionLabelInput.prototype, "EntityName", void 0);
__decorate([
    Field(() => [KeyValuePairInput], { nullable: true }),
    __metadata("design:type", Array)
], CreateVersionLabelInput.prototype, "RecordKeys", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], CreateVersionLabelInput.prototype, "ParentID", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], CreateVersionLabelInput.prototype, "ExternalSystemID", void 0);
__decorate([
    Field(() => Boolean, { nullable: true }),
    __metadata("design:type", Boolean)
], CreateVersionLabelInput.prototype, "IncludeDependencies", void 0);
__decorate([
    Field(() => Int, { nullable: true }),
    __metadata("design:type", Number)
], CreateVersionLabelInput.prototype, "MaxDepth", void 0);
__decorate([
    Field(() => [String], { nullable: true }),
    __metadata("design:type", Array)
], CreateVersionLabelInput.prototype, "ExcludeEntities", void 0);
CreateVersionLabelInput = __decorate([
    InputType()
], CreateVersionLabelInput);
export { CreateVersionLabelInput };
// =========================================================================
// Resolver
// =========================================================================
let VersionHistoryResolver = class VersionHistoryResolver extends ResolverBase {
    async CreateVersionLabel(input, sessionId, pubSub, context) {
        const contextUser = this.GetUserFromPayload(context.userPayload);
        if (!contextUser) {
            return { Success: false, Error: 'Unable to determine user context.' };
        }
        try {
            const engine = new VersionHistoryEngine();
            // Build CompositeKey from input key pairs if provided
            let recordKey;
            if (input.RecordKeys && input.RecordKeys.length > 0) {
                recordKey = new CompositeKey(input.RecordKeys.map(kv => ({
                    FieldName: kv.Key,
                    Value: kv.Value ?? ''
                })));
            }
            // Build progress callback that publishes to PubSub
            const resolvedSessionId = sessionId ?? context.userPayload.sessionId;
            const onProgress = this.buildProgressCallback(pubSub, resolvedSessionId);
            const params = {
                Name: input.Name,
                Description: input.Description,
                Scope: input.Scope ?? 'Record',
                EntityName: input.EntityName,
                RecordKey: recordKey,
                ParentID: input.ParentID,
                ExternalSystemID: input.ExternalSystemID,
                IncludeDependencies: input.IncludeDependencies,
                MaxDepth: input.MaxDepth,
                ExcludeEntities: input.ExcludeEntities,
                OnProgress: onProgress,
            };
            const result = await engine.CreateLabel(params, contextUser);
            LogStatus(`VersionHistory resolver: Label '${input.Name}' created with ${result.CaptureResult.ItemsCaptured} items.`);
            return {
                Success: result.CaptureResult.Success,
                LabelID: result.Label.ID,
                LabelName: result.Label.Name,
                ItemsCaptured: result.CaptureResult.ItemsCaptured,
                SyntheticSnapshotsCreated: result.CaptureResult.SyntheticSnapshotsCreated,
                CaptureErrors: result.CaptureResult.Errors.map(e => ({
                    EntityName: e.EntityName,
                    RecordID: e.RecordID,
                    ErrorMessage: e.ErrorMessage,
                })),
            };
        }
        catch (e) {
            const msg = e instanceof Error ? e.message : String(e);
            LogError(`VersionHistory resolver: CreateLabel failed: ${msg}`);
            return { Success: false, Error: msg };
        }
    }
    /**
     * Build a progress callback that publishes CreateLabelProgress messages
     * to the PubSub system for real-time client consumption.
     */
    buildProgressCallback(pubSub, sessionId) {
        return (progress) => {
            pubSub.publish(PUSH_STATUS_UPDATES_TOPIC, {
                message: JSON.stringify({
                    resolver: 'VersionHistoryResolver',
                    type: 'CreateLabelProgress',
                    status: 'ok',
                    data: progress,
                }),
                sessionId,
            });
        };
    }
};
__decorate([
    Mutation(() => CreateLabelResultOutput),
    __param(0, Arg('input')),
    __param(1, Arg('sessionId', { nullable: true })),
    __param(2, PubSub()),
    __param(3, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [CreateVersionLabelInput, String, PubSubEngine, Object]),
    __metadata("design:returntype", Promise)
], VersionHistoryResolver.prototype, "CreateVersionLabel", null);
VersionHistoryResolver = __decorate([
    Resolver()
], VersionHistoryResolver);
export { VersionHistoryResolver };
//# sourceMappingURL=VersionHistoryResolver.js.map