import { CustomScalar, Scalar } from '@nestjs/graphql';
import { GraphQLError, Kind, ValueNode } from 'graphql';

const validate = (value: string): string => {
  const DATE_REGEX = /^(18|19|20)\d{2}-(0?[1-9]|1[0-2])-(0?[1-9]|[12]\d|3[01])$/;

  if (typeof value !== 'string') {
    throw new TypeError(`Value is not string: ${value}`);
  }

  if (!DATE_REGEX.test(value)) {
    throw new TypeError(`Value is not a valid date: ${value}`);
  }

  const tmp = value.split('-');
  if (tmp[1].length === 1) {
    tmp[1] = '0' + tmp[1];
  }
  if (tmp[2].length === 1) {
    tmp[2] = '0' + tmp[2];
  }
  value = tmp.join('-');

  return value;
};

@Scalar('Date', () => Date)
export class Date implements CustomScalar<string, string> {
  description = 'A date string YYYY-MM-DD'

  parseValue(value: string): string {
    return validate(value)
  }

  serialize(value: string): string {
    return validate(value)
  }

  parseLiteral(ast: ValueNode): string {
    if (ast.kind !== Kind.STRING) {
      throw new GraphQLError(
        `Can only validate strings as date but got a: ${ast.kind}`,
      );
    }
    return validate(ast.value)
  }
}