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 { Arg, Ctx, Int, Query, Resolver } from '@memberjunction/server';
import { MJUser_, MJUserResolverBase } from '../generated/generated.js';
import { GetReadOnlyProvider } from '../util.js';
let UserResolver = class UserResolver extends MJUserResolverBase {
    async CurrentUser(context) {
        // Check API key scope authorization for user read (self)
        await this.CheckAPIKeyScopeAuthorization('user:read', '*', context.userPayload);
        // If userRecord is already available (e.g., from API key auth or system auth),
        // use it directly instead of looking up by email again
        if (context.userPayload.userRecord) {
            // Convert UserInfo to the GraphQL response format
            const userRecord = context.userPayload.userRecord;
            const userData = {
                ID: userRecord.ID,
                Name: userRecord.Name,
                FirstName: userRecord.FirstName,
                LastName: userRecord.LastName,
                Title: userRecord.Title,
                Email: userRecord.Email,
                Type: userRecord.Type,
                IsActive: userRecord.IsActive,
                LinkedRecordType: userRecord.LinkedRecordType,
                EmployeeID: userRecord.EmployeeID,
                LinkedEntityID: userRecord.LinkedEntityID,
                LinkedEntityRecordID: userRecord.LinkedEntityRecordID,
                __mj_CreatedAt: userRecord.__mj_CreatedAt,
                __mj_UpdatedAt: userRecord.__mj_UpdatedAt,
                // Include the UserRoles sub-array for the GraphQL response
                MJUserRoles_UserIDArray: userRecord.UserRoles?.map((r) => ({
                    ID: r.ID,
                    UserID: r.UserID,
                    RoleID: r.RoleID,
                    User: userRecord.Name,
                    Role: r.RoleName,
                    __mj_CreatedAt: r.__mj_CreatedAt,
                    __mj_UpdatedAt: r.__mj_UpdatedAt,
                })) || [],
            };
            console.log('CurrentUser (from userRecord)', userData.Email);
            return this.MapFieldNamesToCodeNames('MJ: Users', userData);
        }
        // Fall back to email lookup for JWT-based auth
        const result = await this.UserByEmail(context.userPayload.email, context);
        console.log('CurrentUser (from email lookup)', result?.Email);
        return result;
    }
    async UserByID(ID, { providers, userPayload }) {
        // Check API key scope authorization for user read
        await this.CheckAPIKeyScopeAuthorization('user:read', ID.toString(), userPayload);
        const provider = GetReadOnlyProvider(providers, { allowFallbackToReadWrite: true });
        const retVal = super.safeFirstArrayElement(await this.findBy(provider, 'MJ: Users', { ID }, userPayload.userRecord));
        return this.MapFieldNamesToCodeNames('MJ: Users', retVal);
    }
    async UserByEmployeeID(EmployeeID, { providers, userPayload }) {
        // Check API key scope authorization for user read
        await this.CheckAPIKeyScopeAuthorization('user:read', EmployeeID.toString(), userPayload);
        const provider = GetReadOnlyProvider(providers, { allowFallbackToReadWrite: true });
        const retVal = super.safeFirstArrayElement(await this.findBy(provider, 'MJ: Users', { EmployeeID }, userPayload.userRecord));
        return this.MapFieldNamesToCodeNames('MJ: Users', retVal);
    }
    async UserByEmail(Email, { providers, userPayload }) {
        // Check API key scope authorization for user read
        await this.CheckAPIKeyScopeAuthorization('user:read', Email, userPayload);
        // const searchEmail = userEmailMap[Email] ?? Email;
        const searchEmail = Email;
        const provider = GetReadOnlyProvider(providers, { allowFallbackToReadWrite: true });
        const returnVal = super.safeFirstArrayElement(await this.findBy(provider, 'MJ: Users', { Email: searchEmail }, userPayload.userRecord));
        return this.MapFieldNamesToCodeNames('MJ: Users', returnVal);
    }
};
__decorate([
    Query(() => MJUser_),
    __param(0, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], UserResolver.prototype, "CurrentUser", null);
__decorate([
    Query(() => MJUser_),
    __param(0, Arg('ID', () => Int)),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Number, Object]),
    __metadata("design:returntype", Promise)
], UserResolver.prototype, "UserByID", null);
__decorate([
    Query(() => MJUser_),
    __param(0, Arg('EmployeeID', () => Int)),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Number, Object]),
    __metadata("design:returntype", Promise)
], UserResolver.prototype, "UserByEmployeeID", null);
__decorate([
    Query(() => MJUser_),
    __param(0, Arg('Email', () => String)),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object]),
    __metadata("design:returntype", Promise)
], UserResolver.prototype, "UserByEmail", null);
UserResolver = __decorate([
    Resolver(MJUser_)
], UserResolver);
export { UserResolver };
export default UserResolver;
//# sourceMappingURL=UserResolver.js.map