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

const validate = (value: string): string => {
  const DATE_REGEX = /^(0?[0-9]|1[0-9]|2[0-3]):(0?[0-9]|[1-5][0-9]):(0?[0-9]|[1-5][0-9])?$/;

  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 time: ${value}`);
  }

  const time = value.split(':');
  if(time[0].length === 1) time[0] = '0' + time[0];
  if(time[1].length === 1) time[1] = '0' + time[1];
  if(time[2].length === 1) time[2] = '0' + time[2];
  return time.join(':');
};

@Scalar('Time', () => Time)
export class Time implements CustomScalar<string, string> {
  description = 'A time string HH:MM:SS'

  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 time but got a: ${ast.kind}`,
      );
    }
    return validate(ast.value)
  }
}