/**
 * Generated by `createschema user.UserExternalIdentity`
 */

const { Text, Select, Relationship } = require('@keystonejs/fields')
const { get } = require('lodash')

const { Json } = require('@open-condo/keystone/fields')
const { historical, versioned, uuided, tracked, softDeleted, dvAndSender } = require('@open-condo/keystone/plugins')
const { GQLListSchema, getById } = require('@open-condo/keystone/schema')

const access = require('@condo/domains/user/access/UserExternalIdentity')
const { IDP_TYPES, RESIDENT } = require('@condo/domains/user/constants/common')


const UserExternalIdentity = new GQLListSchema('UserExternalIdentity', {
    schemaDoc: 'Individual user external identity link. Used primarily for authorization and linking to external identity provider purposes. Think of `User` as a technical entity, not a business actor.',
    fields: {
        user: {
            schemaDoc: 'Link to user',
            type: Relationship,
            ref: 'User',
            isRequired: true,
            knexOptions: { isNotNullable: true }, // Required relationship only!
            kmigratorOptions: { null: false, on_delete: 'models.PROTECT' },
        },
        identityId: {
            schemaDoc: 'External identity id. The value of this field should be populated from an external identity provider',
            type: Text,
            isRequired: true,
        },
        identityType: {
            schemaDoc: 'The type of external identity that was a source for this link',
            type: Select,
            dataType: 'enum',
            options: IDP_TYPES,
            isRequired: true,
        },
        meta: {
            schemaDoc: 'External identity provider user metadata',
            type: Json,
        },
    },
    kmigratorOptions: {
        constraints: [
            {
                type: 'models.UniqueConstraint',
                fields: ['identityId', 'identityType'],
                condition: 'Q(deletedAt__isnull=True)',
                name: 'userExternalIdentity_unique_identityid_and_identitytype',
            },
        ],
    },
    plugins: [
        uuided(),
        versioned(),
        tracked(),
        softDeleted(),
        dvAndSender(),
        historical(),
    ],
    access: {
        read: access.canReadUserExternalIdentities,
        create: access.canManageUserExternalIdentities,
        update: access.canManageUserExternalIdentities,
        delete: false,
        auth: true,
    },
})

module.exports = {
    UserExternalIdentity,
}
