import type { Result } from '@/lib/result';
import type { Context } from 'hono';
import type { ContentfulStatusCode } from 'hono/utils/http-status';
import { mapAppErrorToProblem } from './problem-mapper';

export function handleResult<T>(
  c: Context,
  result: Result<T>,
  successStatus: ContentfulStatusCode = 200
) {
  if (!result.ok) {
    const requestId = c.get('requestId') as string | undefined;
    const instance = requestId ? `/requests/${requestId}` : undefined;
    const problem = mapAppErrorToProblem(result.error, instance);

    return c.json(problem, problem.status);
  }

  return c.json(result.value, successStatus);
}
