import {
  CurrencyData,
  Description,
  Email,
  Language,
  Measure,
  Name,
  Phone,
  Result,
  UTCDateValue,
  UniqueID,
  UnitPrice,
} from "..";
import { UndefinedOr } from "../../../utilities";

export const ensureIdIsValid = (value: string) =>
  UniqueID.create(value, { generateOnEmpty: false });

export const ensureNameIsValid = (value: UndefinedOr<string>, label: string = "name") => {
  const valueOrError = Name.create(value, {
    label,
  });

  return valueOrError.isSuccess ? Result.ok(valueOrError.object) : Result.fail(valueOrError.error);
};

export const ensureEmailIsValid = (value: UndefinedOr<string>, label: string = "email") => {
  const valueOrError = Email.create(value, {
    label,
  });

  return valueOrError.isSuccess ? Result.ok(valueOrError.object) : Result.fail(valueOrError.error);
};

export const ensurePhoneIsValid = (value: UndefinedOr<string>, label: string = "phone") => {
  const valueOrError = Phone.create(value, { label });

  return valueOrError.isSuccess ? Result.ok(valueOrError.object) : Result.fail(valueOrError.error);
};

export const ensureDateIsValid = (value: string): Result<boolean, Error> => {
  const dateOrError = UTCDateValue.create(value);

  return dateOrError.isSuccess ? Result.ok(true) : Result.fail(dateOrError.error);
};

export const ensureCurrencyCodeIsValid = (value: string): Result<boolean, Error> => {
  const currencyOrError = CurrencyData.createFromCode(value);

  return currencyOrError.isSuccess ? Result.ok(true) : Result.fail(currencyOrError.error);
};

export const ensureLanguageCodeIsValid = (value: string): Result<boolean, Error> => {
  const currencyOrError = Language.createFromCode(value);

  return currencyOrError.isSuccess ? Result.ok(true) : Result.fail(currencyOrError.error);
};

export const ensureDescriptionIsValid = (value: string): Result<boolean, Error> => {
  const descriptionOrError = Description.create(value);

  return descriptionOrError.isSuccess ? Result.ok(true) : Result.fail(descriptionOrError.error);
};

/*export const ensureQuantityIsValid = (value: string): Result<boolean, Error> => {
  const descriptionOrError = Quantity.create(value);

  return descriptionOrError.isSuccess ? Result.ok(true) : Result.fail(descriptionOrError.error);
};*/

export const ensureUnitPriceIsValid = (value: any): Result<boolean, Error> => {
  const { amount, currency, scale } = value;
  const descriptionOrError = UnitPrice.create({
    amount,
    currencyCode: currency,
    scale,
  });

  return descriptionOrError.isSuccess ? Result.ok(true) : Result.fail(descriptionOrError.error);
};

export const ensureUnitMeasureIsValid = (value: string): Result<boolean, Error> => {
  const descriptionOrError = Measure.create(value);

  return descriptionOrError.isSuccess ? Result.ok(true) : Result.fail(descriptionOrError.error);
};
