const yup = require('yup');

const { campusCodeToTenantCode } = require('../../helper/helper');

class PersonReference {
  constructor(opt) {
    this.userId = null;
    this.firstName = null;
    this.lastName = null;
    this.email = null;
    this.tenantCode = null;
    this.campusCode = null;

    if (opt) {
      this.fillObject(opt);
    }
  }

  fillObject(opt) {
    this.userId = opt.userId || opt.id || null;
    this.firstName = opt.firstName || null;
    this.lastName = opt.lastName || null;
    this.email = opt.email || null;
    this.tenantCode = opt.tenantCode || campusCodeToTenantCode(opt.campusCode);
    this.campusCode = opt.campusCode || null;
  }

  static schema(options = {}) {
    if (options.yup) {
      return yup
        .object({
          userId: yup.string().required(),
          firstName: yup.string().required(),
          lastName: yup.string().required(),
          email: yup.string().nullable(),
          tenantCode: yup.string().required(),
          campusCode: yup.string().required(),
        })
        .from('id', 'userId');
    }

    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'person-reference.schema.json',
      type: 'object',
      additionalProperties: false,
      properties: {
        userId: { type: 'string' },
        firstName: { type: ['string', 'null'] },
        lastName: { type: ['string', 'null'] },
        tenantCode: { type: ['string', 'null'] }, // TODO:: remove null
        campusCode: { type: 'string' },
        email: { type: ['string', 'null'] },
      },
      required: Object.keys(this),
    };
  }
}

module.exports = PersonReference;
