export interface ApiErrorDetail {
  field: string;
  code: string;
}

export interface ApiError {
  statusCode: number;
  code: string;
  details?: ApiErrorDetail[];
}

export interface ApiErrorResponse {
  success: false;
  error: {
    code: string;
    statusCode: number;
    details?: ApiErrorDetail[];
  };
}

export function isApiError(value: unknown): value is ApiError {
  return (
    typeof value === 'object' &&
    value !== null &&
    'code' in value &&
    typeof (value as ApiError).code === 'string' &&
    'statusCode' in value &&
    typeof (value as ApiError).statusCode === 'number'
  );
}

export function asApiError(value: unknown): ApiError | null {
  if (isApiError(value)) {
    return value;
  }

  if (
    typeof value === 'object' &&
    value !== null &&
    'response' in value &&
    typeof (value as { response?: { data?: ApiErrorResponse } }).response?.data === 'object'
  ) {
    const payload = (value as { response: { data?: ApiErrorResponse } }).response.data;
    if (payload?.success === false && payload.error?.code) {
      return {
        statusCode: payload.error.statusCode,
        code: payload.error.code,
        details: payload.error.details,
      };
    }
  }

  return null;
}

/** @deprecated Use ApiError.code — kept for transitional parsing only. */
export function legacyStatusCode(value: unknown): number | undefined {
  if (isApiError(value)) {
    return value.statusCode;
  }
  if (typeof value === 'object' && value !== null && 'statusCode' in value) {
    const statusCode = (value as { statusCode?: unknown }).statusCode;
    return typeof statusCode === 'number' ? statusCode : undefined;
  }
  return undefined;
}
