const { parsePhoneNumberFromString } = require('libphonenumber-js');
const { StringSchema } = require('yup');

class PhoneSchema extends StringSchema {
  constructor() {
    super({ type: 'phone' });

    this.withMutation((schema) => {
      schema.transform((value) => {
        if (!value || !this.isType(value)) {
          return null;
        }

        const phoneNumber = parsePhoneNumberFromString(value);
        return phoneNumber.number;
      });
    });
  }

  // eslint-disable-next-line class-methods-use-this
  _typeCheck(value) {
    const phoneNumber = parsePhoneNumberFromString(value);

    return Boolean(phoneNumber) && phoneNumber.isValid();
  }
}

module.exports = PhoneSchema;
