import { TypeOrmIdentitySchemaError } from '../errors/TypeOrmIdentitySchemaError';

export function assertNonEmptyString(entityName: string, fieldName: string, value: unknown): asserts value is string {
  if (typeof value !== 'string') {
    throw new TypeOrmIdentitySchemaError({ entityName, fieldName, reason: 'not_string' });
  }

  if (value.trim().length === 0) {
    throw new TypeOrmIdentitySchemaError({ entityName, fieldName, reason: 'empty_string' });
  }
}

export function assertDate(entityName: string, fieldName: string, value: unknown): asserts value is Date {
  if (!(value instanceof Date)) {
    throw new TypeOrmIdentitySchemaError({ entityName, fieldName, reason: 'not_date' });
  }
  if (Number.isNaN(value.getTime())) {
    throw new TypeOrmIdentitySchemaError({ entityName, fieldName, reason: 'invalid_date' });
  }
}

export function assertOptionalStringOrNull(
  entityName: string,
  fieldName: string,
  value: unknown,
): asserts value is string | null | undefined {
  if (value === null || value === undefined) {
    return;
  }

  if (typeof value !== 'string') {
    throw new TypeOrmIdentitySchemaError({ entityName, fieldName, reason: 'not_string' });
  }
}