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

export function assertNonEmptyString(entityName: string, fieldName: string, value: unknown): void {
  if (typeof value !== 'string' || value.trim().length === 0) {
    throw new TypeOrmAdminSchemaError({
      entityName,
      fieldName,
      reason: 'INVALID_STRING',
      message: `Field ${fieldName} must be a non-empty string`,
    });
  }
}

export function assertStringArray(entityName: string, fieldName: string, value: unknown): void {
  if (!Array.isArray(value) || !value.every(item => typeof item === 'string')) {
    throw new TypeOrmAdminSchemaError({
      entityName,
      fieldName,
      reason: 'INVALID_STRING_ARRAY',
      message: `Field ${fieldName} must be an array of strings`,
    });
  }
}

export function assertDate(entityName: string, fieldName: string, value: unknown): void {
  if (!(value instanceof Date) || isNaN(value.getTime())) {
    throw new TypeOrmAdminSchemaError({
      entityName,
      fieldName,
      reason: 'INVALID_DATE',
      message: `Field ${fieldName} must be a valid Date`,
    });
  }
}

export function assertOptionalDate(entityName: string, fieldName: string, value: unknown): void {
  if (value === null || value === undefined) {
    return;
  }
  assertDate(entityName, fieldName, value);
}

export function assertOptionalString(entityName: string, fieldName: string, value: unknown): void {
  if (value === null || value === undefined) {
    return;
  }
  if (typeof value !== 'string') {
    throw new TypeOrmAdminSchemaError({
      entityName,
      fieldName,
      reason: 'INVALID_OPTIONAL_STRING',
      message: `Field ${fieldName} must be a string or undefined`,
    });
  }
}