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 } from "type-graphql";
import { Field, InputType, ObjectType } from "type-graphql";
import { LogError, Metadata } from "@memberjunction/core";
import { GetAPIKeyEngine } from "@memberjunction/api-keys";
import { ResolverBase } from "../generic/ResolverBase.js";
/**
 * Input type for creating a new API key
 */
let CreateAPIKeyInput = class CreateAPIKeyInput {
};
__decorate([
    Field(),
    __metadata("design:type", String)
], CreateAPIKeyInput.prototype, "Label", void 0);
__decorate([
    Field(() => String, { nullable: true }),
    __metadata("design:type", String)
], CreateAPIKeyInput.prototype, "Description", void 0);
__decorate([
    Field(() => Date, { nullable: true }),
    __metadata("design:type", Date)
], CreateAPIKeyInput.prototype, "ExpiresAt", void 0);
__decorate([
    Field(() => [String], { nullable: true }),
    __metadata("design:type", Array)
], CreateAPIKeyInput.prototype, "ScopeIDs", void 0);
CreateAPIKeyInput = __decorate([
    InputType()
], CreateAPIKeyInput);
export { CreateAPIKeyInput };
/**
 * Result type for API key creation
 * Returns the raw key ONCE - it cannot be recovered after this
 */
let CreateAPIKeyResult = class CreateAPIKeyResult {
};
__decorate([
    Field(),
    __metadata("design:type", Boolean)
], CreateAPIKeyResult.prototype, "Success", void 0);
__decorate([
    Field(() => String, { nullable: true }),
    __metadata("design:type", String)
], CreateAPIKeyResult.prototype, "RawKey", void 0);
__decorate([
    Field(() => String, { nullable: true }),
    __metadata("design:type", String)
], CreateAPIKeyResult.prototype, "APIKeyID", void 0);
__decorate([
    Field(() => String, { nullable: true }),
    __metadata("design:type", String)
], CreateAPIKeyResult.prototype, "Error", void 0);
CreateAPIKeyResult = __decorate([
    ObjectType()
], CreateAPIKeyResult);
export { CreateAPIKeyResult };
/**
 * Result type for API key revocation
 */
let RevokeAPIKeyResult = class RevokeAPIKeyResult {
};
__decorate([
    Field(),
    __metadata("design:type", Boolean)
], RevokeAPIKeyResult.prototype, "Success", void 0);
__decorate([
    Field(() => String, { nullable: true }),
    __metadata("design:type", String)
], RevokeAPIKeyResult.prototype, "Error", void 0);
RevokeAPIKeyResult = __decorate([
    ObjectType()
], RevokeAPIKeyResult);
export { RevokeAPIKeyResult };
/**
 * Resolver for API key operations
 * Handles secure server-side API key generation
 */
let APIKeyResolver = class APIKeyResolver extends ResolverBase {
    /**
     * Creates a new API key with proper server-side cryptographic hashing.
     *
     * This mutation:
     * 1. Generates a cryptographically secure API key using APIKeyEngine
     * 2. Stores only the SHA-256 hash in the database (never the raw key)
     * 3. Returns the raw key ONCE - it cannot be recovered after this call
     * 4. Optionally assigns scope permissions to the key
     *
     * @param input The creation parameters
     * @param ctx The GraphQL context with authenticated user
     * @returns The raw key (show once!) and database ID
     */
    async CreateAPIKey(input, ctx) {
        // Check API key scope authorization for API key creation
        await this.CheckAPIKeyScopeAuthorization('apikey:create', '*', ctx.userPayload);
        try {
            // Get the authenticated user
            const user = ctx.userPayload.userRecord;
            if (!user) {
                return {
                    Success: false,
                    Error: "User is not authenticated"
                };
            }
            // Use APIKeyEngine to create the API key with proper server-side crypto
            const apiKeyEngine = GetAPIKeyEngine();
            const result = await apiKeyEngine.CreateAPIKey({
                UserId: user.ID,
                Label: input.Label,
                Description: input.Description,
                ExpiresAt: input.ExpiresAt
            }, user);
            if (!result.Success) {
                return {
                    Success: false,
                    Error: result.Error || "Failed to create API key"
                };
            }
            // Save scope associations if provided
            if (input.ScopeIDs && input.ScopeIDs.length > 0 && result.APIKeyId) {
                await this.saveScopeAssociations(result.APIKeyId, input.ScopeIDs, user);
            }
            return {
                Success: true,
                RawKey: result.RawKey,
                APIKeyID: result.APIKeyId
            };
        }
        catch (e) {
            const error = e;
            LogError(`Error in CreateAPIKey resolver: ${error.message}`);
            return {
                Success: false,
                Error: `Error creating API key: ${error.message}`
            };
        }
    }
    /**
     * Revokes an API key, permanently disabling it.
     *
     * Once revoked, an API key cannot be reactivated. Users must create a new key.
     * This uses APIKeyEngine.RevokeAPIKey() for consistency.
     *
     * @param apiKeyId The database ID of the API key to revoke
     * @param ctx The GraphQL context with authenticated user
     * @returns Success status
     */
    async RevokeAPIKey(apiKeyId, ctx) {
        // Check API key scope authorization for API key revocation
        await this.CheckAPIKeyScopeAuthorization('apikey:revoke', apiKeyId, ctx.userPayload);
        try {
            const user = ctx.userPayload.userRecord;
            if (!user) {
                return {
                    Success: false,
                    Error: "User is not authenticated"
                };
            }
            const apiKeyEngine = GetAPIKeyEngine();
            const result = await apiKeyEngine.RevokeAPIKey(apiKeyId, user);
            if (result) {
                return { Success: true };
            }
            else {
                return {
                    Success: false,
                    Error: "Failed to revoke API key. It may not exist or you may not have permission."
                };
            }
        }
        catch (e) {
            const error = e;
            LogError(`Error in RevokeAPIKey resolver: ${error.message}`);
            return {
                Success: false,
                Error: `Error revoking API key: ${error.message}`
            };
        }
    }
    /**
     * Saves scope associations for the newly created API key
     * @param apiKeyId The ID of the created API key
     * @param scopeIds Array of scope IDs to associate
     * @param user The context user
     */
    async saveScopeAssociations(apiKeyId, scopeIds, user) {
        const md = new Metadata();
        for (const scopeId of scopeIds) {
            try {
                const keyScope = await md.GetEntityObject('MJ: API Key Scopes', user);
                keyScope.APIKeyID = apiKeyId;
                keyScope.ScopeID = scopeId;
                await keyScope.Save();
            }
            catch (error) {
                LogError(`Error saving scope association for API key ${apiKeyId}, scope ${scopeId}: ${error}`);
                // Continue with other scopes even if one fails
            }
        }
    }
};
__decorate([
    Mutation(() => CreateAPIKeyResult),
    __param(0, Arg("input")),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [CreateAPIKeyInput, Object]),
    __metadata("design:returntype", Promise)
], APIKeyResolver.prototype, "CreateAPIKey", null);
__decorate([
    Mutation(() => RevokeAPIKeyResult),
    __param(0, Arg("apiKeyId")),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object]),
    __metadata("design:returntype", Promise)
], APIKeyResolver.prototype, "RevokeAPIKey", null);
APIKeyResolver = __decorate([
    Resolver()
], APIKeyResolver);
export { APIKeyResolver };
//# sourceMappingURL=APIKeyResolver.js.map