import { HttpError } from '../../core/http.js';

export type JsonObject = Record<string, unknown>;

export function jsonObjectValue(value: unknown) {
  return JSON.stringify(value && typeof value === 'object' && !Array.isArray(value) ? value : {});
}

export function jsonArrayValue(value: unknown) {
  return JSON.stringify(Array.isArray(value) ? value : []);
}

export function boolValue(value: unknown, fallback: boolean) {
  return typeof value === 'boolean' ? value : fallback;
}

export function intValue(value: unknown, fallback: number) {
  const numberValue = Number(value ?? fallback);
  return Number.isFinite(numberValue) ? Math.trunc(numberValue) : fallback;
}

export function nullableString(value: unknown) {
  return typeof value === 'string' && value.trim() ? value.trim() : null;
}

export function optionalStatus(value: unknown, allowed: string[], fallback: string) {
  const candidate = nullableString(value) || fallback;
  if (!allowed.includes(candidate)) {
    throw new HttpError(400, `Invalid status: ${candidate}`, 'INVALID_STATUS');
  }
  return candidate;
}
