import { Metadata, RunView, LogError } from '@memberjunction/core';
import { NewUserBase } from './newUsers.js';
import { UserCache } from '@memberjunction/sqlserver-dataprovider';
import { configInfo } from '../config.js';
export class ExampleNewUserSubClass extends NewUserBase {
    async createNewUser(firstName, lastName, email, linkedRecordType = 'None', linkedEntityId, linkedEntityRecordId) {
        try {
            const md = new Metadata();
            const contextUser = UserCache.Instance.Users.find((u) => u.Email.trim().toLowerCase() === configInfo?.userHandling?.contextUserForNewUserCreation?.trim().toLowerCase());
            if (!contextUser) {
                LogError(`Failed to load context user ${configInfo?.userHandling?.contextUserForNewUserCreation}, if you've not specified this on your config.json you must do so. This is the user that is contextually used for creating a new user record dynamically.`);
                return undefined;
            }
            const pEntity = md.Entities.find((e) => e.Name === 'Persons');
            if (!pEntity) {
                LogError('Failed to find Persons entity');
                return undefined;
            }
            let personId;
            const rv = new RunView();
            const viewResults = await rv.RunView({
                EntityName: 'Persons',
                ExtraFilter: `Email = '${email}'`,
            }, contextUser);
            if (viewResults && viewResults.Success && Array.isArray(viewResults.Results) && viewResults.Results.length > 0) {
                const row = viewResults.Results[0];
                personId = row['ID'];
            }
            if (!personId) {
                const p = await md.GetEntityObject('Persons', contextUser);
                p.NewRecord();
                if (await p.Save()) {
                    personId = p.FirstPrimaryKey.Value;
                }
                else {
                    LogError(`Failed to create new person ${firstName} ${lastName} ${email}`);
                }
            }
            return super.createNewUser(firstName, lastName, email, 'Other', pEntity?.ID, personId);
        }
        catch (e) {
            LogError(`Error creating new user ${email} ${e}`);
            return undefined;
        }
    }
}
export function LoadExampleNewUserSubClass() {
}
//# sourceMappingURL=exampleNewUserSubClass.js.map